Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw lines between points in OpenCV?

I have an array of tuples:

a = [(375, 193)
(364, 113)
(277, 20)
(271, 16)
(52, 106)
(133, 266)
(289, 296)
(372, 282)]

How to draw lines between points in OpenCV?

Here is my code that isn't working:

for index, item in enumerate(a): 
    print (item[index]) 
    #cv2.line(image, item[index], item[index + 1], [0, 255, 0], 2) 
like image 769
OPV Avatar asked Oct 27 '25 18:10

OPV


2 Answers

Using draw contours, you can draw the shape all at once.

img = np.zeros([512, 512, 3],np.uint8)
a = np.array([(375, 193), (364, 113), (277, 20), (271, 16), (52, 106), (133, 266), (289, 296), (372, 282)])
cv2.drawContours(img, [a], 0, (255,255,255), 2)

If you don't want the image closed and want to continue how you started:

image = np.zeros([512, 512, 3],np.uint8)
pointsInside = [(375, 193), (364, 113), (277, 20), (271, 16), (52, 106), (133, 266), (289, 296), (372, 282)]

for index, item in enumerate(pointsInside): 
    if index == len(pointsInside) -1:
        break
    cv2.line(image, item, pointsInside[index + 1], [0, 255, 0], 2) 

Regarding your current code, it looks like you are trying to access the next point by indexing the current point. You need to check for the next point in the original array.

A more Pythonic way of doing the second version would be:

for point1, point2 in zip(a, a[1:]): 
    cv2.line(image, point1, point2, [0, 255, 0], 2) 
like image 101
Zev Avatar answered Oct 29 '25 07:10

Zev


If you just want to draw lines, how about cv2.polylines? cv2.drawContours would be preferred when you already have a contours object.

cv2.polylines(image, 
              a, 
              isClosed = False,
              color = (0,255,0),
              thickness = 3, 
              linetype = cv2.LINE_AA)
like image 38
bfris Avatar answered Oct 29 '25 08:10

bfris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!