Untitled

 avatar
unknown
plain_text
5 months ago
4.1 kB
2
Indexable
import random
import time
import json
import cv2
import pytesseract
import csv
from huskylib import HuskyLensLibrary
from pubnub.pubnub import PubNub
from pubnub.pnconfiguration import PNConfiguration

# PubNub configuration
pnconf = PNConfiguration()
pnconf.publish_key = 'pub-c-e47b3d62-b04d-412f-834c-39092e90ec84'  # Set your PubNub publish_key
pnconf.subscribe_key = 'sub-c-28c258f2-2025-4241-9df4-c7f10715cac3'  # Set your PubNub subscribe_key
pnconf.user_id = 'shukla728'
pubnub = PubNub(pnconf)
channel = 'lab1'

# HuskyLens configuration
hl = HuskyLensLibrary("I2C", "", address=0x32)

# Tesseract configuration
pytesseract.pytesseract.tesseract_cmd = "/usr/bin/tesseract"

# CSV file containing authorized license plates
CSV_FILE = "authorized_plates.csv"

# Function to read authorized license plates from a CSV file
def is_plate_authorized(plate_text):
    with open(CSV_FILE, mode="r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            if row["LicensePlate"] == plate_text:
                return True
    return False

# Function to capture an image
def capture_image():
    print("Capturing image...")
    camera = cv2.VideoCapture(0)
    if not camera.isOpened():
        print("Error: Camera not detected!")
        return None

    ret, frame = camera.read()
    if ret:
        image_path = "captured_image.jpg"
        cv2.imwrite(image_path, frame)
        print(f"Image saved at {image_path}")
        camera.release()
        return image_path
    else:
        print("Error: Unable to capture image!")
        camera.release()
        return None

# Function to process image and detect the license plate
def recognize_license_plate(image_path):
    print("Processing image for license plate detection...")
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 100, 200)

    contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        approx = cv2.approxPolyDP(contour, 0.018 * cv2.arcLength(contour, True), True)
        if len(approx) == 4:  # Possible license plate
            x, y, w, h = cv2.boundingRect(contour)
            cropped = gray[y:y+h, x:x+w]
            text = pytesseract.image_to_string(cropped, config="--psm 8").strip()
            print(f"Detected License Plate: {text}")
            return text
    print("No license plate detected.")
    return None

# Publish detection result to PubNub
def publish_result(data):
    exp = {"data": data}
    pubnub.publish().channel(channel).message(exp).sync()
    print(f"Published to channel {channel}: {exp}")

# Main execution
if __name__ == "__main__":
    while True:
        try:
            print("\nWaiting for command...")
            cmd = input("Enter 'capture' to detect plate, 'quit' to exit: ").strip().lower()

            if cmd == "quit":
                print("Exiting...")
                break
            elif cmd == "capture":
                # Capture image
                image_path = capture_image()
                if image_path:
                    # Recognize license plate
                    plate_text = recognize_license_plate(image_path)
                    if plate_text:
                        # Check if the plate is authorized
                        if is_plate_authorized(plate_text):
                            print(f"Access Granted: {plate_text} is authorized.")
                            publish_result(f"Access Granted for {plate_text}.")
                        else:
                            print(f"Access Denied: {plate_text} is not authorized.")
                            publish_result(f"Access Denied for {plate_text}.")
            else:
                print("Unknown command. Please try again.")

        except KeyboardInterrupt:
            print("\nExiting...")
            break
        except Exception as e:
            print(f"An error occurred: {e}")
Editor is loading...
Leave a Comment