我从IP摄像头读取JPG,想要检测损坏的图像 . 这是我加载图像的功能:

from PIL import Image

def getImage(self):
  r=self.http.request('GET', self.snapshotURL, headers=self.headers)
  tmp=io.BytesIO(r.data)
  self.saveTmp(tmp.getvalue())
  image=Image.open(tmp)
  return(image)

如果我收到了损坏的图像,那么's loaded to 1567352 without an error message by Pillow' s Image.open() . 在这种情况下, image.verify() 的结果是 None .

为了能够检查收到的原始数据,它将保存到 saveTmp() 的文件中 .

这是一张图片:http://dede67.bplaced.net/Arduino/ip_cam/corrupt_image.jpg

如果我查看损坏文件的原始数据,该文件以 FF D8 FF E0 10 4A 46 49 46 开头,以 FF D9 结尾 . 这是正常的,没有帮助 .

ImageMagick的 identify 给出了这个:

corrupt_image.bin JPEG 640x480 640x480+0+0 8-bit sRGB 42KB 0.000u 0:00.000

返回码是0 ==没有帮助!

但是如果我用gimp打开文件,gimp告诉我:“损坏的JPEG数据:数据段的过早结束” .

我怎么能(快!)用Pillow来检测损坏的图像...甚至可以用于Python3的任何其他库?

Edit:

现在用这个功能好多了:

def isValid(self):
  if self.valid is None:
    t=datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S-%f")
    fn="/ramdisk/%s__corrupt.jpg"%(t,)
    f=open(fn, "wb")
    f.write(self.raw)
    f.close()
    if self.raw[-2:]!=bytes([255, 217]):
      self.valid=False
      #print("FF D9")
    else:
      rc=subprocess.call(["identify", "-verbose", fn], 
                          stdout=subprocess.DEVNULL, 
                          stderr=subprocess.DEVNULL)
      self.valid=(rc==0)
      #if not self.valid:
      #  print("identify")
    if(self.valid): # temp. not remove corrupt images
      os.remove(fn)
  return(self.valid)

但我仍然得到腐败的图像 . identify -verbosegimp 都没有抱怨这些图片 .

喜欢这个:http://dede67.bplaced.net/Arduino/ip_cam/corrupt_image2.jpg

也许有人有一个想法,如何检测这些剩余的图像!