【发布时间】:2020-03-14 14:29:48
【问题描述】:
我正在尝试从视频中裁剪图像,但没有显示结果。我知道 TypeError 正在发生,因为cropcrop_img 中没有内容,但由于我是opencv 的初学者,所以我不知道它的解决方案。下面的代码是我从项目中复制的,该项目使用带有树莓派和网络摄像头的 opencv 来跟随这条线。现在我正在尝试在我的 Windows 10 上进行测试,因此可能存在一些接口问题。
代码:-
# -*- coding: utf-8 -*-
import numpy as np
import cv2
video_capture = cv2.VideoCapture(-1)
video_capture.set(3, 160)
video_capture.set(4, 120)
while(True):
# Capture the frames
ret, frame = video_capture.read()
#print("image recieved");
#cv2.imshow('frame',ret)
# Crop the image
crop_img = frame[60:120, 0:160]
cv2.imshow("cropped", crop_img)
# Convert to grayscale
gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
# Gaussian blur
blur = cv2.GaussianBlur(gray,(5,5),0)
cv2.imshow('show', blur)
# Color thresholding
ret,thresh = cv2.threshold(blur,60,255,cv2.THRESH_BINARY_INV)
# Find the contours of the frame
contours,hierarchy = cv2.findContours(thresh.copy(), 1, cv2.CHAIN_APPROX_NONE)
# Find the biggest contour (if detected)
if len(contours) > 0:
c = max(contours, key=cv2.contourArea)
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
cv2.line(crop_img,(cx,0),(cx,720),(255,0,0),1)
cv2.line(crop_img,(0,cy),(1280,cy),(255,0,0),1)
cv2.drawContours(crop_img, contours, -1, (0,255,0), 1)
if cx >= 120:
print ("Turn Left!")
if cx < 120 and cx > 50:
print ("On Track!")
if cx <= 50:
print ("Turn Right")
else:
print ("I don't see the line")
#Display the resulting frame
cv2.imshow('frame',crop_img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break\
错误:-
runfile('C:/Users/HP/OneDrive/Desktop/Sultan/Veggitech/Transport robot with Voice Control/Code/Test Code/line_follower_opencv.py', wdir='C:/Users/HP/OneDrive/Desktop/Sultan/Veggitech/Transport robot with Voice Control/Code/Test Code')
Traceback (most recent call last):
File "<ipython-input-2-583afe4334df>", line 1, in <module>
runfile('C:/Users/HP/OneDrive/Desktop/Sultan/Veggitech/Transport robot with Voice Control/Code/Test Code/line_follower_opencv.py', wdir='C:/Users/HP/OneDrive/Desktop/Sultan/Veggitech/Transport robot with Voice Control/Code/Test Code')
File "C:\Users\HP\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\HP\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/HP/OneDrive/Desktop/Sultan/Veggitech/Transport robot with Voice Control/Code/Test Code/line_follower_opencv.py", line 25, in <module>
crop_img = frame[60:120, 0:160]
TypeError: 'NoneType' object is not subscriptable
【问题讨论】:
-
我对 cv2 一无所知,但您的 video_capture 似乎是空的。你能运行这个:
video_capture = cv2.VideoCapture(-1),然后:if video_capture: print('Yes')。这打印是吗? -
实际上我刚刚尝试了 cv2.video_capture(0) 并且有效。尽管现在还有其他错误。 cv2.video_capture(-1) 给出同样的错误
-
video_capture(0) 从默认设备摄像头读取。您还面临哪些其他错误?
-
仅供参考,请针对一个特定问题保留一篇帖子,并单独发布新问题。
-
好吧@FatihAkici,记住这一点
标签: python opencv typeerror opencv3.0 opencv-contour