70 lines
2 KiB
Python
70 lines
2 KiB
Python
import cv2
|
|
import easyocr
|
|
import numpy as np
|
|
from PIL import Image
|
|
from collections import Counter
|
|
|
|
# Initialize the EasyOCR reader
|
|
reader = easyocr.Reader(['en'])
|
|
|
|
def preprocess_image(image):
|
|
# Convert to PIL image for EasyOCR processing
|
|
return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
|
|
|
def recognize_text(image):
|
|
processed_image = preprocess_image(image)
|
|
results = reader.readtext(np.array(processed_image), allowlist='0123456789')
|
|
# Concatenate all recognized text results
|
|
recognized_text = ''.join(result[1] for result in results)
|
|
return recognized_text
|
|
|
|
def format_number(text, length=6):
|
|
# Remove non-numeric characters and pad with zeros if necessary
|
|
formatted = ''.join(filter(str.isdigit, text))
|
|
return formatted.zfill(length)[-length:]
|
|
|
|
def most_common_number(numbers):
|
|
# Find the most common number from the list of numbers
|
|
counter = Counter(numbers)
|
|
most_common = counter.most_common(1)
|
|
return most_common[0][0] if most_common else ''
|
|
|
|
def main():
|
|
cap = cv2.VideoCapture(2)
|
|
|
|
if not cap.isOpened():
|
|
print("Error: Could not open webcam.")
|
|
return
|
|
|
|
print("Press 'q' to quit.")
|
|
frame_count = 0
|
|
text_history = []
|
|
|
|
while True:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
print("Error: Failed to capture image.")
|
|
break
|
|
|
|
# Recognize text from the current frame
|
|
recognized_text = recognize_text(frame)
|
|
formatted_number = format_number(recognized_text)
|
|
|
|
# Update the history with the latest recognized number
|
|
text_history.append(formatted_number)
|
|
|
|
# Keep only the last 10 frames
|
|
if len(text_history) > 20:
|
|
text_history.pop(0)
|
|
|
|
# Determine the most common number from the history
|
|
most_common = most_common_number(text_history)
|
|
print(f"Most common number from last 10 frames: {most_common}")
|
|
|
|
# if cv2.waitKey(1) & 0xFF == ord('q'):
|
|
# break
|
|
|
|
cap.release()
|
|
|
|
if __name__ == "__main__":
|
|
main()
|