import numpy as np
import cv2
from matplotlib import pyplot as plt

images = ['img/1.jpg', 'img/2.jpg', 'img/3.jpg', 'img/26417135.jpg', 'img/ru4018185.jpg']

processed_plates = []

for img_path in images:
    image = cv2.imread(img_path)

    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(img_gray, 100, 200, cv2.THRESH_TOZERO_INV)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for i in range(len(contours)):
        x, y, w, h = cv2.boundingRect(contours[i])
        a = w * h
        aspectRatio = float(w) / h
        if aspectRatio >= 3 and a > 600:
            approx = cv2.approxPolyDP(contours[i], 0.05 * cv2.arcLength(contours[i], True), True)
            if len(approx) <= 4 and x > 15:
                width = w
                height = h
                start_x = x
                start_y = y
                end_x = start_x + width
                end_y = start_y + height
                break

    plate = image[start_y:end_y, start_x:end_x]

    gray = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    largest_contour = max(contours, key=cv2.contourArea)
    rect = cv2.minAreaRect(largest_contour)
    box = cv2.boxPoints(rect)
    box = np.intp(box)
    angle = rect[-1]

    if angle < -45:
        angle += 90
    if angle < 90:
        (h, w) = plate.shape[:2]
        center = (w // 2, h // 2)
        M = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated = cv2.warpAffine(plate, M, (w, h))
    else:
        angle = 0.5
        (h, w) = plate.shape[:2]
        center = (w // 2, h // 2)
        M = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated = cv2.warpAffine(plate, M, (w, h))

    processed_plates.append(rotated)

for i, rotated_plate in enumerate(processed_plates):
    cv2.imshow(f'Номер {i+1}', rotated_plate)

cv2.waitKey(0)
cv2.destroyAllWindows()
