以下是图像阈值处理的代码我在第22行收到错误
是: -
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
在此代码中,我想从摄像机捕获图像帧,然后对捕获的图像帧执行各种阈值处理操作。
我在不同的时间存储了图像帧。我的目标是在视频中分割移动的对象。因此我正在应用阈值操作。
有人有任何想法,怎么做?
提前致谢。
import cv2
import numpy as np
import time
from matplotlib import pyplot as plt
import sys
cam = cv2.VideoCapture(0)
while(cam.isOpened()):
ret, frame = cam.read() #Keep on capturing the frames continuously
while (ret==True):
#img = cv2.imread('/home/shrikrishna/Detection&Tracking/OpenCV-Tutorial',6)
cv2.imwrite('At time'+ str(time.clock()) + '.jpg', frame)
img2 = cv2.imread('At time'+ str(time.clock()) + '.jpg',6)
t = str(time.clock())
cv2.imshow('Orignal',frame)
k = cv2.waitKey(0) & 0xffff
if(k==27):
#img = cv2.imread('At time'+ str(time.clock()) + '.jpg',6)
break
if(k==ord('q')):
sys.exit(0)
break
#cv2.imwrite('At time'+ t + '.jpg', frame)
img = cv2.imread('At time'+ t + '.jpg',6)
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in xrange(6):
plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
答案 0 :(得分:0)
在下一行中,您将图像读入彩色图像(基于第二个参数 - 标记)。
img = cv2.imread('At time'+ t + '.jpg',6)
这意味着img
包含3个通道,在Python中由3维数组表示。
您可以立即使用此图像作为阈值处理源:
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
根据documentation,threshold()
的第一个参数是:
这意味着您需要单个频道图片,例如灰度图像:
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh1 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
# ...
另一种选择是首先将图像作为灰度读取:
img_gray = cv2.imread('At time'+ t + '.jpg',0)
# ...