x, y, w, h = cv2.boundingRect(contours[0]) cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-ykpa0m5d\opencv\modules\imgproc\src\shapedescr.cpp:874: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::pointSetBoundingRect'
时间: 2023-08-28 18:19:59 浏览: 91
这个错误是由于 cv2.boundingRect() 函数的参数传递错误导致的。这个函数需要一个轮廓列表作为参数,而你可能是没有成功找到轮廓或没有将其转换为列表形式。请检查你的代码,确保找到了正确的轮廓,并将其传递给 cv2.boundingRect() 函数。另外,也可以检查一下轮廓列表的数据类型,确保它们是 CV_32F 或 CV_32S 类型。
相关问题
def get_postion(image): img = cv2.imread(image) blurred = cv2.GaussianBlur(image,(5,5),0,0) canny = cv2.Canny(blurred,0,100) contours,hierarchy=cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print(len(contours)) for contour in contours: x,y,w,h = cv2.boundingRect(contour) area = cv2.contourArea(contour) loop = cv2.arcLength(contour,True) if 152<loop<162 and 1444<area<1849: x,y,w,h = cv2.boundingRect(contour) cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2) cv2.imwrite("111.jpg",image) return x return 0帮我优化一下代码 用中文
请问需要对以下代码进行优化:
```
def get_postion(image):
img = cv2.imread(image)
blurred = cv2.GaussianBlur(image,(5,5),0,0)
canny = cv2.Canny(blurred,0,100)
contours,hierarchy=cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
for contour in contours:
x,y,w,h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
loop = cv2.arcLength(contour,True)
if 152<loop<162 and 1444<area<1849:
x,y,w,h = cv2.boundingRect(contour)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
cv2.imwrite("111.jpg",image)
return x
return 0
```
还请提供一些更具体的优化需求和背景信息,这样我才能更好地为您提供帮助。
contours, hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: perimeter = cv2.arcLength(cnt, True) if perimeter > 500: # 画出矩形框 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2把这段改为大于500小于1000
修改后的代码如下:
```
contours, hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
perimeter = cv2.arcLength(cnt, True)
if 500 < perimeter < 1000: # 修改条件为周长大于500小于1000
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
```
这段代码会找出周长大于500小于1000的所有轮廓,并在原始图像frame上画出其包围矩形框。