File size: 5,191 Bytes
94a2a81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab46679
94a2a81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from flask import Flask, Response, request, jsonify
import cv2
from flask_cors import CORS 
import pytesseract
import numpy as np
import os
import uuid

from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi

uri = "mongodb+srv://cse443Prudhvi:pEjVbWv6oJHaHSJA@cluster0.7ournot.mongodb.net/"
# Create a new client and connect to the server


cluster = MongoClient(uri)
db = cluster['cseData']  # Replace '<dbname>' with your actual database name
collection = db['numberPlates'] 



FRAME_WIDTH = 640
FRAME_HEIGHT = 480
PLATE_CASCADE = cv2.CascadeClassifier('/HGDeploy/flaskapp/haarcascade_russian_plate_number (1).xml')
MIN_AREA = 300
COLOR = (255, 0, 255) 


# Declare a variable with the type ndarray[Any, dtype[generic]]
img_roi: np.ndarray = np.array([1, 2, 3])

app = Flask(__name__)
CORS(app)
counter = 0  # Counter for image filenames
 
def generate_frames(n):
    cap = cv2.VideoCapture(0) 
    
    global img_roi
    while cap.isOpened():
        # read the camera frame
        success, frame = cap.read()
        
        if not success:
            break
        else:
            img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            number_plates = PLATE_CASCADE.detectMultiScale(img_gray, 1.3, 7)

            # Iterate through detected plates
            
            for (x, y, w, h) in number_plates:
                area = (w * h)+100
                if area > MIN_AREA:
                    # Draw rectangle around the plate
                    cv2.rectangle(frame, (x, y), (x + w, y + h), COLOR, 2)
                    # Add text label
                    cv2.putText(frame, "License Plate", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, COLOR, 2)
                    # Show region of interest (ROI)
                    img_roi = frame[y:y + h , x:x + w ]
                    

        ret, buffer = cv2.imencode('.jpg', frame)
        frame_bytes = buffer.tobytes()
        
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
@app.route('/')
def index():
    return "Hello World"


@app.route('/video')
def video():
    return Response(generate_frames(0), mimetype='multipart/x-mixed-replace; boundary=frame')




@app.route('/save', methods=['POST'])
def save():

    global counter
    global img_roi
    cv2.imwrite(f"/Users/prudhviraj/Documents/CSE443/img/{counter}.png", img_roi)

    image = f"/Users/prudhviraj/Documents/CSE443/img/{counter}.png"
    pytesseract.pytesseract.tesseract_cmd = '/opt/homebrew/bin/tesseract'
    extracted_text = pytesseract.image_to_string(image)

    new_text=''
    alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    num="0123456789"
    for i in extracted_text:
        if i in alpha or i in num:
            new_text+=i
    print(new_text)
    print("Yes!!!!!")
    # collection.insert_one({"number":f"{new_text}"})
    
    counter += 1
    return new_text

UPLOAD_FOLDER = '/Users/prudhviraj/Documents/CSE443/img'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_image():
    # check if the post request has the file part
    if 'image' not in request.files:
        return jsonify({"error": "No image part in the request"}), 400

    image_file = request.files['image']

    # if user does not select file, browser also submits an empty part without filename
    if image_file.filename == '':
        return jsonify({"error": "No selected image file"}), 400

    if image_file and allowed_file(image_file.filename):
        filename = str(uuid.uuid4()) + '.' + image_file.filename.rsplit('.', 1)[1].lower()
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        image_file.save(filepath)
        
        print(filepath)
        frame = cv2.imread(filepath)
        # success, frame = image.read()

        img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        number_plates = PLATE_CASCADE.detectMultiScale(img_gray, 1.3, 7)

        for (x, y, w, h) in number_plates:
                area = w * h
                if area > MIN_AREA:
                    # Draw rectangle around the plate
                    cv2.rectangle(frame, (x, y), (x + w, y + h), COLOR, 2)
                    # Add text label
                    cv2.putText(frame, "License Plate", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, COLOR, 2)
                    # Show region of interest (ROI)
                    img_roi = frame[y:y + h, x:x + w]
        pytesseract.pytesseract.tesseract_cmd = '/opt/homebrew/bin/tesseract'
        extracted_text = pytesseract.image_to_string(img_roi)

        new_text=''
        alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        num="0123456789"
        for i in extracted_text:
            if i in alpha or i in num:
                new_text+=i
        print(new_text)
        return jsonify({"success": "Image uploaded successfully", "filename": filename}), 200

    else:
        return jsonify({"error": "File type not allowed"}), 400



if __name__ == '__main__':
    app.run(debug=True)