Amazing-Python-Scripts

Форк
0
256 строк · 8.0 Кб
1
from tkinter import *
2
from PIL import Image, ImageTk
3
from tkinter import filedialog
4
import object_detection as od
5
import imageio
6
import cv2
7

8

9
class Window(Frame):
10
    def __init__(self, master=None):
11
        Frame.__init__(self, master)
12

13
        self.master = master
14
        self.pos = []
15
        self.line = []
16
        self.rect = []
17
        self.master.title("GUI")
18
        self.pack(fill=BOTH, expand=1)
19

20
        self.counter = 0
21

22
        menu = Menu(self.master)
23
        self.master.config(menu=menu)
24

25
        file = Menu(menu)
26
        file.add_command(label="Open", command=self.open_file)
27
        file.add_command(label="Exit", command=self.client_exit)
28
        menu.add_cascade(label="File", menu=file)
29

30
        analyze = Menu(menu)
31
        analyze.add_command(label="Region of Interest",
32
                            command=self.regionOfInterest)
33
        menu.add_cascade(label="Analyze", menu=analyze)
34

35
        self.filename = "Images/home.jpg"
36
        self.imgSize = Image.open(self.filename)
37
        self.tkimage = ImageTk.PhotoImage(self.imgSize)
38
        self.w, self.h = (1366, 768)
39

40
        self.canvas = Canvas(master=root, width=self.w, height=self.h)
41
        self.canvas.create_image(20, 20, image=self.tkimage, anchor='nw')
42
        self.canvas.pack()
43

44
    def open_file(self):
45
        self.filename = filedialog.askopenfilename()
46

47
        cap = cv2.VideoCapture(self.filename)
48

49
        reader = imageio.get_reader(self.filename)
50
        fps = reader.get_meta_data()['fps']
51

52
        ret, image = cap.read()
53
        cv2.imwrite(
54
            'G:/Traffic Violation Detection/Traffic Signal Violation Detection System/Images/preview.jpg', image)
55

56
        self.show_image(
57
            'G:/Traffic Violation Detection/Traffic Signal Violation Detection System/Images/preview.jpg')
58

59
    def show_image(self, frame):
60
        self.imgSize = Image.open(frame)
61
        self.tkimage = ImageTk.PhotoImage(self.imgSize)
62
        self.w, self.h = (1366, 768)
63

64
        self.canvas.destroy()
65

66
        self.canvas = Canvas(master=root, width=self.w, height=self.h)
67
        self.canvas.create_image(0, 0, image=self.tkimage, anchor='nw')
68
        self.canvas.pack()
69

70
    def regionOfInterest(self):
71
        root.config(cursor="plus")
72
        self.canvas.bind("<Button-1>", self.imgClick)
73

74
    def client_exit(self):
75
        exit()
76

77
    def imgClick(self, event):
78

79
        if self.counter < 2:
80
            x = int(self.canvas.canvasx(event.x))
81
            y = int(self.canvas.canvasy(event.y))
82
            self.line.append((x, y))
83
            self.pos.append(self.canvas.create_line(
84
                x - 5, y, x + 5, y, fill="red", tags="crosshair"))
85
            self.pos.append(self.canvas.create_line(
86
                x, y - 5, x, y + 5, fill="red", tags="crosshair"))
87
            self.counter += 1
88

89
        # elif self.counter < 4:
90
        #     x = int(self.canvas.canvasx(event.x))
91
        #     y = int(self.canvas.canvasy(event.y))
92
        #     self.rect.append((x, y))
93
        #     self.pos.append(self.canvas.create_line(x - 5, y, x + 5, y, fill="red", tags="crosshair"))
94
        #     self.pos.append(self.canvas.create_line(x, y - 5, x, y + 5, fill="red", tags="crosshair"))
95
        #     self.counter += 1
96

97
        if self.counter == 2:
98
            # unbinding action with mouse-click
99
            self.canvas.unbind("<Button-1>")
100
            root.config(cursor="arrow")
101
            self.counter = 0
102

103
            # show created virtual line
104
            print(self.line)
105
            print(self.rect)
106
            img = cv2.imread(
107
                'G:/Traffic Violation Detection/Traffic Signal Violation Detection System/Images/preview.jpg')
108
            cv2.line(img, self.line[0], self.line[1], (0, 255, 0), 3)
109
            cv2.imwrite(
110
                'G:/Traffic Violation Detection/Traffic Signal Violation Detection System/Images/copy.jpg', img)
111
            self.show_image(
112
                'G:/Traffic Violation Detection/Traffic Signal Violation Detection System/Images/copy.jpg')
113

114
            # for demonstration
115
            # (rxmin, rymin) = self.rect[0]
116
            # (rxmax, rymax) = self.rect[1]
117

118
            # tf = False
119
            # tf |= self.intersection(self.line[0], self.line[1], (rxmin, rymin), (rxmin, rymax))
120
            # print(tf)
121
            # tf |= self.intersection(self.line[0], self.line[1], (rxmax, rymin), (rxmax, rymax))
122
            # print(tf)
123
            # tf |= self.intersection(self.line[0], self.line[1], (rxmin, rymin), (rxmax, rymin))
124
            # print(tf)
125
            # tf |= self.intersection(self.line[0], self.line[1], (rxmin, rymax), (rxmax, rymax))
126
            # print(tf)
127

128
            # cv2.line(img, self.line[0], self.line[1], (0, 255, 0), 3)
129

130
            # if tf:
131
            #     cv2.rectangle(img, (rxmin,rymin), (rxmax,rymax), (255,0,0), 3)
132
            # else:
133
            #     cv2.rectangle(img, (rxmin,rymin), (rxmax,rymax), (0,255,0), 3)
134

135
            # cv2.imshow('traffic violation', img)
136

137
            # image processing
138
            self.main_process()
139
            print("Executed Successfully!!!")
140

141
            # clearing things
142
            self.line.clear()
143
            self.rect.clear()
144
            for i in self.pos:
145
                self.canvas.delete(i)
146

147
    def intersection(self, p, q, r, t):
148
        print(p, q, r, t)
149
        (x1, y1) = p
150
        (x2, y2) = q
151

152
        (x3, y3) = r
153
        (x4, y4) = t
154

155
        a1 = y1-y2
156
        b1 = x2-x1
157
        c1 = x1*y2-x2*y1
158

159
        a2 = y3-y4
160
        b2 = x4-x3
161
        c2 = x3*y4-x4*y3
162

163
        if (a1*b2-a2*b1 == 0):
164
            return False
165
        print((a1, b1, c1), (a2, b2, c2))
166
        x = (b1*c2 - b2*c1) / (a1*b2 - a2*b1)
167
        y = (a2*c1 - a1*c2) / (a1*b2 - a2*b1)
168
        print((x, y))
169

170
        if x1 > x2:
171
            tmp = x1
172
            x1 = x2
173
            x2 = tmp
174
        if y1 > y2:
175
            tmp = y1
176
            y1 = y2
177
            y2 = tmp
178
        if x3 > x4:
179
            tmp = x3
180
            x3 = x4
181
            x4 = tmp
182
        if y3 > y4:
183
            tmp = y3
184
            y3 = y4
185
            y4 = tmp
186

187
        if x >= x1 and x <= x2 and y >= y1 and y <= y2 and x >= x3 and x <= x4 and y >= y3 and y <= y4:
188
            return True
189
        else:
190
            return False
191

192
    def main_process(self):
193

194
        video_src = self.filename
195

196
        cap = cv2.VideoCapture(video_src)
197

198
        reader = imageio.get_reader(video_src)
199
        fps = reader.get_meta_data()['fps']
200
        writer = imageio.get_writer(
201
            'G:/Traffic Violation Detection/Traffic Signal Violation Detection System/Resources/output/output.mp4', fps=fps)
202

203
        j = 1
204
        while True:
205
            ret, image = cap.read()
206

207
            if (type(image) == type(None)):
208
                writer.close()
209
                break
210

211
            image_h, image_w, _ = image.shape
212
            new_image = od.preprocess_input(image, od.net_h, od.net_w)
213

214
            # run the prediction
215
            yolos = od.yolov3.predict(new_image)
216
            boxes = []
217

218
            for i in range(len(yolos)):
219
                # decode the output of the network
220
                boxes += od.decode_netout(yolos[i][0], od.anchors[i],
221
                                          od.obj_thresh, od.nms_thresh, od.net_h, od.net_w)
222

223
            # correct the sizes of the bounding boxes
224
            od.correct_yolo_boxes(boxes, image_h, image_w, od.net_h, od.net_w)
225

226
            # suppress non-maximal boxes
227
            od.do_nms(boxes, od.nms_thresh)
228

229
            # draw bounding boxes on the image using labels
230
            image2 = od.draw_boxes(
231
                image, boxes, self.line, od.labels, od.obj_thresh, j)
232

233
            writer.append_data(image2)
234

235
            # cv2.imwrite('E:/Virtual Traffic Light Violation Detection System/Images/frame'+str(j)+'.jpg', image2)
236
            # self.show_image('E:/Virtual Traffic Light Violation Detection System/Images/frame'+str(j)+'.jpg')
237

238
            cv2.imshow('Traffic Violation', image2)
239

240
            print(j)
241

242
            if cv2.waitKey(10) & 0xFF == ord('q'):
243
                writer.close()
244
                break
245

246
            j = j+1
247

248
        cv2.destroyAllWindows()
249

250

251
root = Tk()
252
app = Window(root)
253
root.geometry("%dx%d" % (535, 380))
254
root.title("Traffic Violation")
255

256
root.mainloop()
257

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.