[SOLVED] How can I draw multiple lines with opencv, at the same time?

Issue

I’m using opencv to identify some lines and am getting a numpy array returned as follows:

print(lines)
print(type(lines))

[[[884 605 894 605]]

 [[854 603 899 603]]

 [[864 606 883 606]]

 [[679 401 697 401]]

 [[751 551 787 551]]

 [[764 554 777 554]]

 [[664 404 679 404]]]
<class 'numpy.ndarray'>

When I pass this to cv2.polylines, it doesn’t draw anything. Things I’ve tried include unpacking the ndarray, using cv2.line in a loop, and cv.rectangle in a loop, making a completely new python list from the array.

So far only line and rectangle draw anything, but they dont draw on the image all at once which is why I want polylines to work. For reference, I am taking continuous screenshots, and on each screenshot only one thing is drawn, instead of all the lines.


    def drawlines(original_img, lines):
        try:

            img = cv.polylines(original_img, [lines], False, (0, 255, 0), 4)
            return img
        
        except:
            return original_img

Solution

Something like this?:

def drawlines(original_img, lines):
        try:
            isClosed = True
            color = (0, 255, 0)
            thickness = 2

            points = []
            for line in lines:
                points.append([line[0][0], line[0][1]])
                points.append([line[0][2], line[0][3]])
                points = np.array(points, np.int32).reshape((-1, 1, 2))

                img = cv.polylines(original_img, [points], isClosed, color, thickness)
            return img

        except:
            return original_img

More info:
https://www.geeksforgeeks.org/python-opencv-cv2-polylines-method/

Answered By – J͓uul

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *