draw line on image using mouse click python code example
Example: draw line from 2 mouse event in image python
import cv2
class DrawLineWidget(object):
def __init__(self):
self.original_image = cv2.imread('1.jpg')
self.clone = self.original_image.copy()
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.extract_coordinates)
self.image_coordinates = []
def extract_coordinates(self, event, x, y, flags, parameters):
if event == cv2.EVENT_LBUTTONDOWN:
self.image_coordinates = [(x,y)]
elif event == cv2.EVENT_LBUTTONUP:
self.image_coordinates.append((x,y))
print('Starting: {}, Ending: {}'.format(self.image_coordinates[0], self.image_coordinates[1]))
cv2.line(self.clone, self.image_coordinates[0], self.image_coordinates[1], (36,255,12), 2)
cv2.imshow("image", self.clone)
elif event == cv2.EVENT_RBUTTONDOWN:
self.clone = self.original_image.copy()
def show_image(self):
return self.clone
if __name__ == '__main__':
draw_line_widget = DrawLineWidget()
while True:
cv2.imshow('image', draw_line_widget.show_image())
key = cv2.waitKey(1)
if key == ord('q'):
cv2.destroyAllWindows()
exit(1)