draw line from 2 mouse event in image python

Solutions on MaxInterview for draw line from 2 mouse event in image python by the best coders in the world

showing results for - "draw line from 2 mouse event in image python"
Florent
05 Apr 2020
1import cv2
2
3class DrawLineWidget(object):
4    def __init__(self):
5        self.original_image = cv2.imread('1.jpg')
6        self.clone = self.original_image.copy()
7
8        cv2.namedWindow('image')
9        cv2.setMouseCallback('image', self.extract_coordinates)
10
11        # List to store start/end points
12        self.image_coordinates = []
13
14    def extract_coordinates(self, event, x, y, flags, parameters):
15        # Record starting (x,y) coordinates on left mouse button click
16        if event == cv2.EVENT_LBUTTONDOWN:
17            self.image_coordinates = [(x,y)]
18
19        # Record ending (x,y) coordintes on left mouse bottom release
20        elif event == cv2.EVENT_LBUTTONUP:
21            self.image_coordinates.append((x,y))
22            print('Starting: {}, Ending: {}'.format(self.image_coordinates[0], self.image_coordinates[1]))
23
24            # Draw line
25            cv2.line(self.clone, self.image_coordinates[0], self.image_coordinates[1], (36,255,12), 2)
26            cv2.imshow("image", self.clone) 
27
28        # Clear drawing boxes on right mouse button click
29        elif event == cv2.EVENT_RBUTTONDOWN:
30            self.clone = self.original_image.copy()
31
32    def show_image(self):
33        return self.clone
34
35if __name__ == '__main__':
36    draw_line_widget = DrawLineWidget()
37    while True:
38        cv2.imshow('image', draw_line_widget.show_image())
39        key = cv2.waitKey(1)
40
41        # Close program with keyboard 'q'
42        if key == ord('q'):
43            cv2.destroyAllWindows()
44            exit(1)
45