import cv2 import numpy as np def getContours(img): contours, hierarchy = cv2.findContours( img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE ) for cnt in contours: area = cv2.contourArea(cnt) print(area) if area > 500: cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3) path = "/home/robot/code.py/shape.jpg" img = cv2.imread(path) imgContour = img.copy() imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1) imgCanny = cv2.Canny(imgBlur, 50, 50) getContours(imgCanny) imgBlank = np.zeros_like(img) cv2.imshow("Original", img) cv2.imshow("Gray", imgGray) cv2.imshow("Blur", imgBlur) cv2.imshow("Canny", imgCanny) cv2.imshow("Blank", imgContour) cv2.waitKey(0)有什么bug
时间: 2023-11-30 17:02:16 浏览: 70
代码中存在两个问题:
1. 在导入 cv2 模块时,应该使用以下方式:
```python
import cv2
import numpy as np
```
2. 在调用 ``cv2.drawContours()`` 函数时,需要将第一个参数改为 ``imgContour``,因为 ``imgContour`` 是我们要绘制轮廓的图像。
修改后的代码如下:
```python
import cv2
import numpy as np
def getContours(img):
contours, hierarchy = cv2.findContours(
img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
)
for cnt in contours:
area = cv2.contourArea(cnt)
print(area)
if area > 500:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
path = "/home/robot/code.py/shape.jpg"
img = cv2.imread(path)
imgContour = img.copy()
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1)
imgCanny = cv2.Canny(imgBlur, 50, 50)
getContours(imgCanny)
imgBlank = np.zeros_like(img)
cv2.imshow("Original", img)
cv2.imshow("Gray", imgGray)
cv2.imshow("Blur", imgBlur)
cv2.imshow("Canny", imgCanny)
cv2.imshow("Contour", imgContour)
cv2.waitKey(0)
```
阅读全文