[原創] 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()
運行結果如下: