OpenCV图像减法与Numpy减法

2024-04-29 03:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着跟踪下一张照片和前一张有多大的不同,假设场景中有一些移动。决定在两个jpg图像之间应用相应像素值的减法,然后计算所得矩阵的平均值,以检查其是否低于或低于某个阈值水平(供进一步分析)。

减法采用cv2减法和np减法。我注意到结果有很大的不同。看起来numpy以某种方式扩展了直方图和标准化的结果值,但是为什么呢?

图像通过cv2.open加载。我知道这种方法使用BGR顺序的通道,但它不能解释发生了什么。加载的图像是具有np.uint值的numpy nd.array。使用Python 3.7开发Spyder。

Edit:cv2.imread中的参数0告诉以灰度加载图像

OpenCV subtraction result

Numpy subtraction result

#loading images

img_cam0 = cv2.imread(r'C:\Users\Krzysztof\Desktop\1.jpg',0)
img_cam1 = cv2.imread(r'C:\Users\Krzysztof\Desktop\2.jpg', 0)
print('img0 type:',type(img_cam0), 'and shape:', img_cam0.shape)
print('img1 type:',type(img_cam1),'and shape:', np.shape(img_cam1))
print('\n')

#opencv subtraction

cv2_subt = cv2.subtract(img_cam0,img_cam1)
cv2_mean = cv2.mean(cv2_subt)

print('open cv mean is:', cv2_mean)
f.show_im(cv2_subt, 'cv2_subtr')

#np subtraction and mean

np_subtr = np.subtract(img_cam0, img_cam1)
np_mean = np.mean(np_subtr)

print('numpy mean is:', np_mean)
f.show_im(np_subtr, 'np_subtr')

Tags: 图像numpyimgtypenpmeancv2jpg
1条回答
网友
1楼 · 发布于 2024-04-29 03:11:11

区别很简单——饱和和不饱和。

^{}执行饱和。根据文件:

dst(I) = saturate(src1(I) - src2(I))

^{}只执行常规减法,因此结果受integer overflow(即值环绕)约束。


Saturation means that when the input value v is out of the range of the target type, the result is not formed just by taking low bits of the input, but instead the value is clipped. For example:

uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)

Such clipping is done when the target type is unsigned char , signed char , unsigned short or signed short . For 32-bit integers, no clipping is done.


示例

>>> import cv2
>>> import numpy as np

>>> a = np.arange(9, dtype=np.uint8).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=uint8)
>>> b = np.full((3,3), 4, np.uint8)
>>> b
array([[4, 4, 4],
       [4, 4, 4],
       [4, 4, 4]], dtype=uint8)

>>> np.subtract(b,a)
array([[  4,   3,   2],
       [  1,   0, 255],
       [254, 253, 252]], dtype=uint8)

>>> cv2.subtract(b,a)
array([[4, 3, 2],
       [1, 0, 0],
       [0, 0, 0]], dtype=uint8)

相关问题 更多 >