import cv2 import numpy as np def drawshape(src,points): i = 0 while i<len(points): if(i==len(points)-1): x, y = points[i][0] x1, y1 = points[0][0] cv2.line(src, (x, y), (x1, y1), (0, 0, 255 ), 3) else: x, y = points[i][0] x1, y1 = points[i + 1][0] cv2.line(src, (x, y), (x1, y1), (0, 0, 255), 3) i = i + 1 img=cv2.imread("C:/Users/CHL/Pictures/Screenshots/hand.png") print(img.shape) #装变为单通道 gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #二值化 ret,binary=cv2.threshold(gray,150,255,cv2.THRESH_BINARY) #轮廓查找 contours,hierarchy=cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(img,contours,-1,(0,255,0),0) #多边形逼近,参数分别为轮廓、精度、是否闭合 e=20 approx=cv2.approxPolyDP(contours[0],e,True) drawshape(img,approx) print(approx) #凸包,参数分别为轮廓,绘制方向 #cv2.convexHull(approx) cv2.imshow('img',img) cv2.waitKey(0) 帮我修改这段代码,因为他不能正常画线
时间: 2024-04-08 09:34:34 浏览: 61
当您说这段代码不能正常画线时,我注意到在绘制线段时,使用的颜色参数是`(0, 0, 255)`,这代表红色。如果您希望绘制蓝色的线段,请将颜色参数修改为`(255, 0, 0)`。另外,您还可以检查`drawshape`函数中的循环是否正确,以确保每个点都正确连接。
以下是修改后的代码:
```python
import cv2
import numpy as np
def drawshape(src, points):
i = 0
while i < len(points):
if i == len(points) - 1:
x, y = points[i][0]
x1, y1 = points[0][0]
cv2.line(src, (x, y), (x1, y1), (255, 0, 0), 3) # 修改颜色参数为蓝色
else:
x, y = points[i][0]
x1, y1 = points[i + 1][0]
cv2.line(src, (x, y), (x1, y1), (255, 0, 0), 3) # 修改颜色参数为蓝色
i = i + 1
img = cv2.imread("C:/Users/CHL/Pictures/Screenshots/hand.png")
print(img.shape)
# 转变为单通道
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# 轮廓查找
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 0)
# 多边形逼近,参数分别为轮廓、精度、是否闭合
e = 20
approx = cv2.approxPolyDP(contours[0], e, True)
drawshape(img, approx)
print(approx)
# 凸包,参数分别为轮廓,绘制方向
# cv2.convexHull(approx)
cv2.imshow('img', img)
cv2.waitKey(0)
```
请尝试运行修改后的代码,看看是否能够正确绘制蓝色的线段。
阅读全文