【问题标题】:IndexError in finding the pixel difference of two imagesIndexError 在查找两个图像的像素差异时
【发布时间】:2016-04-07 02:24:11
【问题描述】:

以下是在 python 中使用 opencv 来查找相同大小的两个图像的像素差异的代码。但是,它在最后一行给了我一个错误,我不知道如何修复它。

if h1==h2:
    if w1==w2:
        c=np.zeros((h1,w1,3),np.uint8)
        for i in range(img1.shape[0]):
            for j in range(img1.shape[1]):
                c[j][i]=img1[j][i]-img2[j][i]

IndexError:索引 480 超出轴 0 的范围,大小为 480

【问题讨论】:

  • 感谢您的宝贵回复.. 但我尝试了您建议的这种方法。但它返回错误 TypeError: list indices must be integers, not tuple 如何将结果存储为数组以显示它作为图像。

标签: python opencv numpy


【解决方案1】:

您混淆了索引; i 属于 img1.shape[0]

img1[j][i]-img2[j][i]

也就是说,numpy 可以为你矢量化这个过程,你可以简单地做

if img1.shape == img2.shape:
    c = img1 - img2

但是,您必须小心您的数据类型。如果一张图片的像素为0,另一张的像素为32怎么办?

>>> np.uint8(0) - np.uint8(32)

Warning (from warnings module):
  File "__main__", line 2
RuntimeWarning: overflow encountered in ubyte_scalars
224

您想将它们转换为整数以获得差异,如果您想将差异保持在 0-255 的范围内,您可以取其绝对值。

c = img1.astype(int) - img2.astype(int)
# you can optionally do the following depending on what you want to do next
c = np.abs(c).astype(np.uint8)

OpenCV 说一个函数可以为你实现所有这些,cv2.absdiff()

c = cv2.absdiff(img1, img2)

【讨论】:

  • 你可能想提到cv2.absdiff,因为这个问题被标记为OpenCV
  • @Miki 是的,我只是在阅读它并尝试使用该软件包。感谢您让我的生活更轻松。
猜你喜欢
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
相关资源
最近更新 更多