OpenCV/videoKard.py

63 lines
1.9 KiB
Python
Raw Permalink Normal View History

import cv2
2024-02-02 11:45:41 +00:00
import numpy as np
2024-02-02 11:45:41 +00:00
def detect_rectangle(frame, template, threshold):
result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
2024-02-02 11:45:41 +00:00
# Check if the maximum correlation coefficient is above the threshold
print(max_val)
2024-02-02 11:45:41 +00:00
if max_val >= threshold:
# Define the rectangle area
h, w = template.shape[:2]
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
2024-02-02 11:45:41 +00:00
# Draw rectangle on the frame
cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)
2024-02-02 11:45:41 +00:00
# Crop the region within the rectangle
cropped_region = frame[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]
2024-02-02 11:45:41 +00:00
# Save the cropped region as an image
cv2.imwrite('output_vlad.png', cropped_region)
exit(0)
2024-02-02 11:45:41 +00:00
return frame
2024-02-02 11:45:41 +00:00
def main():
# Load the template image (ID card template)
template = cv2.imread('img/imgsmall.png', 0) # Make sure to replace with the actual template image
2024-02-02 11:45:41 +00:00
# Start capturing video from the default camera (you can change the index if using an external camera)
cap = cv2.VideoCapture(0)
2024-02-02 11:45:41 +00:00
while True:
# Read a frame from the camera
ret, frame = cap.read()
2024-02-02 11:45:41 +00:00
if not ret:
print("Failed to capture frame")
break
2024-02-02 11:45:41 +00:00
# Convert the frame to grayscale
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
2024-02-02 11:45:41 +00:00
# Detect rectangles in the frame with a threshold
frame_with_rectangle = detect_rectangle(gray_frame, template, threshold=0.5)
2024-02-02 11:45:41 +00:00
# Display the result
cv2.imshow('Object Detection', frame_with_rectangle)
2024-02-02 11:45:41 +00:00
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
2024-02-02 11:45:41 +00:00
# Release the camera and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()
2024-02-02 11:45:41 +00:00
if __name__ == "__main__":
main()