Amazing-Python-Scripts
113 строк · 3.3 Кб
1import os
2import numpy as np
3import cv2
4import pickle
5import argparse
6import matplotlib.pyplot as plt
7from matplotlib.patches import Polygon
8from matplotlib.widgets import PolygonSelector
9from matplotlib.collections import PatchCollection
10from shapely.geometry import box
11from shapely.geometry import Polygon as shapely_poly
12
13points = []
14prev_points = []
15patches = []
16total_points = []
17breaker = False
18
19
20class SelectFromCollection(object):
21def __init__(self, ax):
22self.canvas = ax.figure.canvas
23
24self.poly = PolygonSelector(ax, self.onselect)
25self.ind = []
26
27def onselect(self, verts):
28global points
29points = verts
30self.canvas.draw_idle()
31
32def disconnect(self):
33self.poly.disconnect_events()
34self.canvas.draw_idle()
35
36
37def break_loop(event):
38global breaker
39global globSelect
40global savePath
41if event.key == 'b':
42globSelect.disconnect()
43if os.path.exists(savePath):
44os.remove(savePath)
45
46print("Data saved in " + savePath + " file")
47with open(savePath, 'wb') as f:
48pickle.dump(total_points, f, protocol=pickle.HIGHEST_PROTOCOL)
49exit()
50
51
52def onkeypress(event):
53global points, prev_points, total_points
54if event.key == 'n':
55pts = np.array(points, dtype=np.int32)
56if points != prev_points and len(set(points)) == 4:
57print("Points: " + str(pts))
58patches.append(Polygon(pts))
59total_points.append(pts)
60prev_points = points
61
62
63def process_video(video_path, out_file):
64global globSelect
65global savePath
66savePath = out_file if out_file.endswith(".p") else out_file + ".p"
67
68print("\n> Select a region in the figure by enclosing it within a quadrilateral.")
69print("> Press the 'f' key to go full screen.")
70print("> Press the 'esc' key to discard the current quadrilateral.")
71print("> Try holding the 'shift' key to move all of the vertices.")
72print("> Try holding the 'ctrl' key to move a single vertex.")
73print("> After marking a quadrilateral, press 'n' to save the current quadrilateral, and then press 'q' to start marking a new quadrilateral.")
74print("> When you are done, press 'b' to exit the program.\n")
75
76video_capture = cv2.VideoCapture(video_path)
77cnt = 0
78rgb_image = None
79while video_capture.isOpened():
80success, frame = video_capture.read()
81if not success:
82break
83if cnt == 5:
84rgb_image = frame[:, :, ::-1]
85cnt += 1
86video_capture.release()
87
88fig, ax = plt.subplots()
89image = rgb_image
90ax.imshow(image)
91
92p = PatchCollection(patches, alpha=0.7)
93p.set_array(10 * np.ones(len(patches)))
94ax.add_collection(p)
95
96globSelect = SelectFromCollection(ax)
97bbox = plt.connect('key_press_event', onkeypress)
98break_event = plt.connect('key_press_event', break_loop)
99plt.show()
100globSelect.disconnect()
101
102
103if __name__ == '__main__':
104parser = argparse.ArgumentParser()
105parser.add_argument('video_path', help="Path of the video file")
106parser.add_argument(
107'--out_file', help="Name of the output file", default="regions.p")
108args = parser.parse_args()
109
110video_path = args.video_path
111out_file = args.out_file
112
113process_video(video_path, out_file)
114