Untitled

 avatar
unknown
plain_text
2 years ago
15 kB
1
Indexable
main.py


'''
def cmd():
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Failed to open the camera")
        exit()
    ret, frame = cap.read()
    if not ret:
        print("Failed to capture frame in cmd")
        exit()
    if cap.isOpened():
        ser = serial.Serial('COM9', 9600)
        hex_command = '8101040734FF'
        command = binascii.unhexlify(hex_command)
        ser.write(command)
        video_output()
        #response = ser.readline()
        #print("Response: ", response)
    cap.release()
    cv2.destroyAllWindows()


# over_speed=overspeed()
cmd1=cmd()
'''

import binascii
import datetime
import tkinter
from tkinter import messagebox
import serial
import time
import cv2
import customtkinter
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk

global icr_var


class Speed_Hunter_Start:
    def __init__(self, window):
        self.icr_var = tk.BooleanVar(value=False)
        self.checkbox_1_state = False
        self.window = window
        self.window.title("Speed Hunter III")
        # configure grid layout (4x4)
        self.window.grid_columnconfigure(1, weight=1)
        self.window.grid_columnconfigure((2, 3), weight=0)
        self.window.grid_rowconfigure((0, 1, 2), weight=1)
        self.checkbox_1_state = False

        self.cap = cv2.VideoCapture(0)  # Replace '0' with the appropriate camera index or device ID

        self.canvas = customtkinter.CTkCanvas(self.window, width=720, height=520)  # use (640,480) while developing
        self.canvas.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")

        self.sidebar_frame = customtkinter.CTkFrame(self.window)
        self.sidebar_frame.grid(row=1, column=0)
        self.sidebar_button_1 = customtkinter.CTkButton(self.sidebar_frame, text="Tools",
                                                        command=self.setting_window_event)
        self.sidebar_button_1.grid(row=1, column=0, padx=20, pady=10)
        self.sidebar_button_2 = customtkinter.CTkButton(self.sidebar_frame, text="Auto Capture",
                                                        command=self.setting_window_event)
        self.sidebar_button_2.grid(row=1, column=1, padx=20, pady=10)
        self.sidebar_button_3 = customtkinter.CTkButton(self.sidebar_frame, text="Manual Capture",
                                                        command=self.setting_window_event)
        self.sidebar_button_3.grid(row=1, column=2, padx=20, pady=10)
        self.sidebar_button_4 = customtkinter.CTkButton(self.sidebar_frame, text="Snapshot",
                                                        command=self.snapshot)
        self.sidebar_button_4.grid(row=1, column=3, padx=20, pady=10)
        self.sidebar_button_5 = customtkinter.CTkButton(self.sidebar_frame, text="Maps",
                                                        command=self.open_maps)
        self.sidebar_button_5.grid(row=1, column=4, padx=20, pady=10)
        self.exit_button = customtkinter.CTkButton(self.sidebar_frame, fg_color="red", hover_color="green", text="Exit",
                                                   command=self.exit_app)
        self.exit_button.grid(row=1, column=5, padx=20, pady=10)


        #  create zoom button frame
        self.zoombutton_frame = customtkinter.CTkFrame(self.window)
        self.zoombutton_frame.grid(row=0, column=1, sticky="nw")
        self.label_zoom_group = customtkinter.CTkLabel(master=self.zoombutton_frame, text="Zoom:")
        self.label_zoom_group.grid(row=0, column=0, padx=10, pady=10, sticky="n")
        self.zoom_button_1 = customtkinter.CTkButton(self.zoombutton_frame, text="+")
        self.zoom_button_1.grid(row=1, column=0, padx=20, pady=10)
        self.zoom_button_2 = customtkinter.CTkButton(self.zoombutton_frame, text="-")
        self.zoom_button_2.grid(row=2, column=0, padx=20, pady=10)

        self.zoom_button_1.bind("<ButtonPress-1>", lambda event: self.zoom_in())
        self.zoom_button_1.bind("<ButtonRelease-1>", lambda event: self.zoom_in_stop())
        self.zoom_button_2.bind("<ButtonPress-1>", lambda event: self.zoom_out())
        self.zoom_button_2.bind("<ButtonRelease-1>", lambda event: self.zoom_out_stop())

        self.show_frame()

    #  <-------------------------Settings window code starts------------------------------------------>
    def setting_window_event(self):
        setting_window = tkinter.Toplevel()
        setting_window.title("Tools")
        #setting_window.attributes('-toolwindow', True)
        setting_window.geometry(f"{640}x{480}+0+0")
        setting_window.attributes('-topmost', True)
        setting_window.grid_columnconfigure(0,weight=1)
        setting_window.grid_rowconfigure(1,weight=1)


        # create sidebar frame with widgets
        sidebar_frame = customtkinter.CTkFrame(setting_window, corner_radius=0)
        sidebar_frame.grid(row=0, column=0, rowspan=4, padx=(20, 20), pady=(20, 0), sticky="n")
        sidebar_frame.grid_rowconfigure(4, weight=1)
        logo_label = customtkinter.CTkLabel(sidebar_frame, text="Speed Hunter X",
                                            font=customtkinter.CTkFont(size=20, weight="bold"))
        logo_label.grid(row=0, column=0, padx=20, pady=(20, 10))
        sidebar_button_1 = customtkinter.CTkButton(sidebar_frame, text="Add New Location")
        sidebar_button_1.grid(row=1, column=0, padx=20, pady=10)
        sidebar_button_2 = customtkinter.CTkButton(sidebar_frame, text="Add New Officer")
        sidebar_button_2.grid(row=2, column=0, padx=20, pady=10)
        sidebar_button_3 = customtkinter.CTkButton(sidebar_frame, text="Change Officer")
        sidebar_button_3.grid(row=3, column=0, padx=20, pady=10)
        appearance_mode_label = customtkinter.CTkLabel(sidebar_frame, text="Appearance Mode:", anchor="w")
        appearance_mode_label.grid(row=5, column=0, padx=20, pady=(10, 0))
        appearance_mode_optionmenu = customtkinter.CTkOptionMenu(sidebar_frame,
                                                                 values=["Light", "Dark", "System"],
                                                                 command=self.change_appearance_mode_event)
        appearance_mode_optionmenu.grid(row=6, column=0, padx=20, pady=(10, 10))
        appearance_mode_optionmenu.set("System")

        focus_label = customtkinter.CTkLabel(sidebar_frame, text="Focus Mode:", anchor="w")
        focus_label.grid(row=7, column=0, padx=20, pady=(10, 0))
        focus_optionmenu = customtkinter.CTkOptionMenu(sidebar_frame,
                                                       values=["Auto", "Manual"],
                                                       command=self.change_focus_event)
        focus_optionmenu.grid(row=8, column=0, padx=20, pady=(10, 20))
        focus_optionmenu.set("Auto")

        # create ICR checkbox frame
        checkbox_slider_frame = customtkinter.CTkFrame(setting_window)
        checkbox_slider_frame.grid(row=0, column=1, padx=(20, 20), pady=(20, 0), sticky="n")
        checkbox_1 = customtkinter.CTkCheckBox(master=checkbox_slider_frame, variable=self.icr_var,
                                               onvalue=True, offvalue=False,
                                               text="ICR Mode On/Off", command=self.icr_mode)
        checkbox_1.grid(row=0, column=0, padx=20, pady=10)

        checkbox_1.select() if self.checkbox_1_state else checkbox_1.deselect()

    #  <---------------------Settings window code ends------------------------------------>

    def open_maps(self):
        latitude = 13.020480
        longitude = 77.615920
        url = f"https://www.google.com/maps/search/?api=1&query={latitude},{longitude}"

    def snapshot(self):
        if not self.cap.isOpened():
            print("Failed to open the camera")
            exit()
        ret, frame = self.cap.read()
        if not ret:
            print("Failed to capture frame")
            exit()
        cur_date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        file_path = f"C:/Users/msiplaccouts/PycharmProjects/camera_test/images/{cur_date}.jpg"
        cv2.putText(frame, cur_date, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
        cv2.imwrite(file_path, frame)
        messagebox.showinfo("Speed Hunter X","Snapshot Captured!")

    # <------------------------------ICR Mode Function------------------------------------>
    def icr_mode(self):
        self.icr_var = not self.icr_var
        print(self.icr_var)
        if self.icr_var:
            ser = serial.Serial('COM9', 9600)
            hex_command = '8101040103FF'  # ICR OFF COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)
            self.checkbox_1_state = False
            print("work in off")
        else:
            ser = serial.Serial('COM9', 9600)
            hex_command = '8101040102FF'  # ICR ON COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)
            time.sleep(0.6)
            hex_command = '81010414030AFF'  # ICR ON WITH HLC ON MAX-LEVEL = 10 COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)
            self.checkbox_1_state = True
            print("work in on")

    def change_appearance_mode_event(self, new_appearance_mode: str):
        customtkinter.set_appearance_mode(new_appearance_mode)

    # <------------------------------Auto/Manual Focus Function------------------------------------>
    def change_focus_event(self, new_focus: str):
        if new_focus == "Auto":
            if self.cap.isOpened():
                ser = serial.Serial('COM9', 9600)
                hex_command = '8101043802FF'  # AUTO-FOCUS ON COMMAND
                command = binascii.unhexlify(hex_command)
                ser.write(command)
            else:
                print("Unable to open camera")
        else:
            if self.cap.isOpened():
                ser = serial.Serial('COM9', 9600)
                hex_command = '8101043803FF'  # MANUAL-FOCUS ON COMMAND
                command = binascii.unhexlify(hex_command)
                ser.write(command)
            else:
                print("Unable to open camera")

    # <------------------------------Display Video Function------------------------------------>
    def show_frame(self):
        if not self.cap.isOpened():
            print("Failed to open the camera in show_frame method")
            exit()
        ret, frame = self.cap.read()
        if not ret:
            print("Failed to capture frame")
            exit()
        if ret:
            frame = cv2.resize(frame, (1280,720))  # (640,480)
            image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

            h,w, _ = image.shape
            center_x = w // 2
            center_y = h // 2
            target_size = 15
            cv2.rectangle(image,(center_x - target_size,center_y - target_size),
                          (center_x + target_size, center_y + target_size),(0,0,255),2)
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            cv2.putText(image,current_time,(10,30),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
            img = ImageTk.PhotoImage(Image.fromarray(image))
            self.canvas.create_image(0, 0, anchor=tk.NW, image=img)
            self.canvas.image = img
        self.window.after(5, self.show_frame)

    # <------------------------------zoom out functions------------------------------------>
    def zoom_out(self):
        if self.cap.isOpened():
            ser = serial.Serial('COM9', 9600)
            hex_command = '8101040734FF'  # ZOOM OUT CONTINUOUSLY COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)

    def zoom_out_stop(self):
        if self.cap.isOpened():
            ser = serial.Serial('COM9', 9600)
            hex_command = '8101040734FF8101040700FF81097E7E00FF'  # ZOOM OUT ONCE COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)

    # <------------------------------zoom in functions------------------------------------>
    def zoom_in(self):
        if self.cap.isOpened():
            ser = serial.Serial('COM9', 9600)
            hex_command = '8101040724FF'  # ZOOM IN CONTINUOUSLY COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)

    def zoom_in_stop(self):

        if self.cap.isOpened():
            ser = serial.Serial('COM9', 9600)
            hex_command = '8101040724FF8101040700FF81097E7E00FF'  # ZOOM IN ONCE COMMAND
            command = binascii.unhexlify(hex_command)
            ser.write(command)

    # <------------------------------exit gui function------------------------------------->
    def exit_app(self):
        ser = serial.Serial('COM9', 9600)
        hex_command = '8101041903FF'  # RESET CAMERA COMMAND
        command = binascii.unhexlify(hex_command)
        ser.write(command)
        ser.close()
        self.cap.release()
        self.window.destroy()


window = customtkinter.CTk()  # Create the Tkinter window

# screen_width = window.winfo_screenwidth()
# screen_height = window.winfo_screenheight()


window.geometry(f"{1920}x{1080}+0+0")
#window.attributes('-fullscreen',True)
customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("blue")
app = Speed_Hunter_Start(window)  # Create the CameraApp object
window.mainloop()  # Run the Tkinter event loop




laser.py

import struct

import serial

ser = serial.Serial('COM1', 9600)
ser.write(b'SN\r\n')  # to find serial number of laser device
ser.write(b'DL2\r\n')  # to set lower distance limit
ser.write(b'DH300\r\n')  # to set upper distance limit
ser.write(b'SO\r\n')  # to start laser device
filename = 'data.txt'
file = open(filename, 'w')
try:
    while True:

        data = ser.read()
        decoded_data=data.decode('utf-8')
        print(decoded_data,end='')
        file.write(decoded_data)
        file.flush()

except KeyboardInterrupt:
    file.close()
    ser.close()

with open("data.txt", 'r+') as fp:
    lines = fp.readlines()
    fp.seek(0)
    fp.truncate()
    fp.writelines(lines[1:])

output_list = []
with open('data.txt', 'r') as file:
    for line in file:
        line = line.strip()
        if ':' in line:
            parts = line.split(':')
            print(parts)
            for item in parts:
                item = item.strip('\x00')
                if '\x00' in item:
                    speed, dist =item.split('\x00')
                    print(speed, dist)

''' if item:
                    key, value = item.split('.')
                    output_list.append({key: value})

print(output_list)'''



'''
with open('data.txt', 'r') as file:
    for line in file:
        line = line.strip()
        if ':' in line:
            parts = line.split(':')
            print(parts)
            speed = parts[0].strip()'''



Editor is loading...