Hi i am trying to draw multiple polygons using opencv and python please anyone can help me how to draw multiple polygons using mouse clicks setmousecallback method.
class PolygonDrawer(object):
def __init__(self, window_name):
self.window_name = window_name # Name for our window
self.done = False # Flag signalling we're done
self.current = (0, 0) # Current position, so we can draw the line-in-progress
self.points = [] # List of points defining our polygon
def on_mouse(self, event, x, y, buttons, user_param):
if self.done: # Nothing more to do
return
if event == cv2.EVENT_MOUSEMOVE:
self.current = (x, y)
elif event == cv2.EVENT_LBUTTONDOWN:
print("Adding point #%d with position(%d,%d)" % (len(self.points), x, y))
self.points.append((x, y))
elif event == cv2.EVENT_RBUTTONDOWN:
print("Completing polygon with %d points." % len(self.points))
self.done = True
def run(self):
cv2.namedWindow(self.window_name, flags=cv2.WINDOW_AUTOSIZE)
cv2.imshow(self.window_name, np.zeros(CANVAS_SIZE, np.uint8))
cv2.waitKey(1)
cv2.setMouseCallback(self.window_name, self.on_mouse)
while(not self.done):
canvas = np.zeros(CANVAS_SIZE, np.uint8)
if (len(self.points) > 0):
cv2.polylines(canvas, np.array([self.points]), False, FINAL_LINE_COLOR, 1)
cv2.line(canvas, self.points[-1], self.current, WORKING_LINE_COLOR)
cv2.imshow(self.window_name, canvas)
if cv2.waitKey(50) == 27: # ESC hit
self.done = True
canvas = np.zeros(CANVAS_SIZE, np.uint8)
if (len(self.points) > 0):
cv2.fillPoly(canvas, np.array([self.points]), FINAL_LINE_COLOR)
cv2.imshow(self.window_name, canvas)
cv2.waitKey()
cv2.destroyWindow(self.window_name)
return canvas
if __name__ == "__main__":
pd = PolygonDrawer("Polygon")
image = pd.run()
cv2.imwrite("polygon.png", image)
print("Polygon = %s" % pd.points)
using this i can draw only single polygon but i need to draw multiple polygons i am using while(1): but it is not correct i think , please any one can sort it out
↧