[原创] python下 opencv图像减法测试
Author: chad
Mail: [email protected]
视频图像动态检测原理实验
实验原理,输入两幅图像s1 / s2 ,然后将两张图片相减,如果变换的像素超过一定阈值则说明图像中有运动物体。
实验1:
直接使用opencv提供的图像减法功能:
Cv2.imread
默认读取的是全彩图片,为了便于处理,我们需要使用灰度图,调用如下:
cv2.imread( picpathname, 0 )
使用参数0指定读取灰度图。
图像相减的时候直接s1 - s2 即可,结果如下图:
局部放大图:
隐约可以看到有变换的数字。
彩图直接相减结果如下:
局部放大图:
上面的结果非常混乱,这是为什么呢?!!
最后发现原因如下:
➜ ~ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> x = np.uint8(10)
>>> y = np.uint8(12)
>>> x-y
__main__:1: RuntimeWarning: overflow encountered in ubyte_scalars
254
>>> y-x
2
当结果为负值导致计算溢出,进而导致出错。
实验2:
解决办法就是自己写图像减法程序,python程序如下:
程序中增加了二值化部分,阈值小于20的统统为0,大于的为255.
#!/usr/bin/env python
import cv2
import numpy as np
ph1 = "/home/chad/011.jpg"
ph2 = "/home/chad/014.jpg"
threshod= 20
s1 = cv2.imread(ph1,0)
s2 = cv2.imread(ph2,0)
emptyimg = np.zeros(s1.shape,np.uint8)
def pic_sub(dest,s1,s2):
for x in range(dest.shape[0]):
for y in range(dest.shape[1]):
if(s2[x,y] > s1[x,y]):
dest[x,y] = s2[x,y] - s1[x,y]
else:
dest[x,y] = s1[x,y] - s2[x,y]
if(dest[x,y] < threshod):
dest[x,y] = 0
else:
dest[x,y] = 255
pic_sub(emptyimg,s1,s2)
cv2.namedWindow("s1")
cv2.namedWindow("s2")
cv2.namedWindow("result")
cv2.imshow("s1",s1)
cv2.imshow("s2",s2)
cv2.imshow("result",emptyimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果如下: