|
import cv2 |
|
import matplotlib.pyplot as plt |
|
from ultralytics import YOLO |
|
import pytesseract |
|
from pytesseract import Output |
|
|
|
def predict_and_plot(model, path_test_car): |
|
""" |
|
Predicts and plots the bounding boxes on the given test image using the trained YOLO model. |
|
Also performs OCR on the detected bounding boxes to extract text. |
|
|
|
Parameters: |
|
model (YOLO): The trained YOLO model. |
|
path_test_car (str): Path to the test image file. |
|
""" |
|
|
|
results = model.predict(path_test_car, device='CPU') |
|
|
|
|
|
image = cv2.imread(path_test_car) |
|
|
|
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) |
|
|
|
|
|
for result in results: |
|
for box in result.boxes: |
|
|
|
x1, y1, x2, y2 = map(int, box.xyxy[0]) |
|
|
|
confidence = box.conf[0] |
|
|
|
|
|
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) |
|
|
|
cv2.putText(image, f'{confidence*100:.2f}%', (x1, y1 - 10), |
|
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2) |
|
|
|
|
|
roi = image[y1:y2, x1:x2] |
|
|
|
|
|
text = pytesseract.image_to_string(roi, config='--psm 6') |
|
print(f"Detected text: {text}") |
|
|
|
|
|
plt.imshow(image) |
|
plt.axis('off') |
|
plt.show() |
|
|
|
if __name__ == "__main__": |
|
model = YOLO('best.pt') |
|
predict_and_plot(model, "Dataset/images/Cars9.png") |
|
|