2016-08-03 65 views
0

我想計算兩個圖像之間的差異。我只對圖像的某個部分的差值感興趣。爲此,我將圖像的所需部分複製到臨時圖像,並對這些圖像進行操作。但是,使用http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html上指定的像素分配。這給出,OpenCV Python將圖像的某些部分複製到另一個

ball = img[280:340, 330:390] img[273:333, 100:160] = ball

使用相似的邏輯,我寫了一個Python程序,

import cv2 
import numpy as np 

img_file = 'carparking2_1.jpg' 
img = cv2.imread(img_file, cv2.IMREAD_COLOR) 
img_withoutcar = 'carparking2_1.jpg' 
img_withcar = 'carparking2.jpg' 

img1 = img_withoutcar[47:151, 106:157] 
img2 = img_withcar[47:151, 106:157] 

diff1 = cv2.absdiff(img1, img2) 
diff2 = cv2.absdiff(img1, img1) 

print 'RGB shape: ', img.shape  # Rows, cols, channels 
print 'Difference with car and without: ', diff1 
print 'Difference with car and with car: ', diff2 

然而,即時得到輸出消息:

File "D:/Projects/IoT Smart Parking/differenceinframes.py", line 8, in <module> 
    img1 = img_withoutcar[47:151, 106:157] 
TypeError: string indices must be integers, not tuple 

我在Windows 10上運行Python 2.7與OpenCV 3.1.0。

回答

1

你得到的錯誤是因爲你的命令試圖將字符串'carparking2_1.jpg'分割成好像它是圖像數據。

#First assign the file names: 
file_name_without_car='carparking2_1.jpg' 
file_name_with_car='carparking2.jpg' 

#load the images 
img_withoutcar= cv2.imread(file_name_without_car, cv2.IMREAD_COLOR) 
img_withcar= cv2.imread(file_name_with_car, cv2.IMREAD_COLOR) 

#now you can slice regions of the images 
#note that color images have a third dimension for color channel. 
img1 = img_withoutcar[47:151, 106:157,:] 
img2 = img_withcar[47:151, 106:157,:] 
相關問題