Я пытаюсь обнаружить различные формы, используя источник видео, используя opencv с Python, однако мой код обнаруживает только «призрачные круги», я не знаю, почему происходит такое поведение. Я использую это видео в своем коде.
здесь полный комментарий моего кода:
import cv2
# Initialize counters for detected shapes
triangle_count = 0
quadrilateral_count = 0
pentagon_count = 0
hexagon_count = 0
circle_count = 0
# Horizontal reference line (middle of the frame)
line_y = 240 # Adjust according to the height of the video
# Read the video from file
video_path = 'video.mp4' # Video path
cap = cv2.VideoCapture(video_path)
# Check if the video is loaded correctly
if not cap.isOpened():
print("Error opening video.")
exit()
# Process the video frame by frame
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break # Exit when the video ends
# Create a copy of the original frame to use later
original = frame.copy()
# Convert the frame from BGR to HSV
hsv_image = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Convert the HSV image to grayscale
gray_image = cv2.cvtColor(hsv_image, cv2.COLOR_BGR2GRAY)
# Apply Otsu thresholding to binarize the image
ret, otsu = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Apply the mask to the original image
image = cv2.bitwise_and(original, original, mask=otsu)
# Find contours in the binary image
contours, _ = cv2.findContours(otsu, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw the horizontal reference line
cv2.line(frame, (0, line_y), (frame.shape[1], line_y), (0, 255, 0), 2)
# Process each contour
for i, contour in enumerate(contours):
if i == 0: # Ignore the largest outer contour
continue
# Calculate the area of the contour
contour_area = cv2.contourArea(contour)
# Filter out small objects based on area
if contour_area < 300: # Adjust the minimum area value
continue
# Approximate the shape of the contour
epsilon = 0.01 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# Calculate the center of the object (bounding box coordinates)
x, y, w, h = cv2.boundingRect(approx)
center_y = y + h // 2 # Y coordinate of the object's center
# Check if the object crosses the horizontal reference line
if line_y - 10 line_y: # Only classify if the shape crosses the line
if len(approx) == 3:
# Triangle
shape_counts['TRI'] += 1
cv2.putText(frame, 'TRI', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2, cv2.LINE_AA)
elif 4
Подробнее здесь: [url]https://stackoverflow.com/questions/79289405/why-my-code-cant-detect-any-triangle-square-or-another-shape-using-opencv[/url]
Я пытаюсь обнаружить различные формы, используя источник видео, используя opencv с Python, однако мой код обнаруживает только «призрачные круги», я не знаю, почему происходит такое поведение. Я использую это видео в своем коде. здесь полный комментарий моего кода: [code]import cv2
# Horizontal reference line (middle of the frame) line_y = 240 # Adjust according to the height of the video
# Read the video from file video_path = 'video.mp4' # Video path cap = cv2.VideoCapture(video_path)
# Check if the video is loaded correctly if not cap.isOpened(): print("Error opening video.") exit()
# Process the video frame by frame while cap.isOpened(): ret, frame = cap.read() if not ret: break # Exit when the video ends
# Create a copy of the original frame to use later original = frame.copy()
# Convert the frame from BGR to HSV hsv_image = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Convert the HSV image to grayscale gray_image = cv2.cvtColor(hsv_image, cv2.COLOR_BGR2GRAY)
# Apply Otsu thresholding to binarize the image ret, otsu = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Apply the mask to the original image image = cv2.bitwise_and(original, original, mask=otsu)
# Find contours in the binary image contours, _ = cv2.findContours(otsu, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw the horizontal reference line cv2.line(frame, (0, line_y), (frame.shape[1], line_y), (0, 255, 0), 2)
# Process each contour for i, contour in enumerate(contours): if i == 0: # Ignore the largest outer contour continue
# Calculate the area of the contour contour_area = cv2.contourArea(contour)
# Filter out small objects based on area if contour_area < 300: # Adjust the minimum area value continue
# Approximate the shape of the contour epsilon = 0.01 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True)
# Calculate the center of the object (bounding box coordinates) x, y, w, h = cv2.boundingRect(approx) center_y = y + h // 2 # Y coordinate of the object's center
# Check if the object crosses the horizontal reference line if line_y - 10 line_y: # Only classify if the shape crosses the line if len(approx) == 3: # Triangle shape_counts['TRI'] += 1 cv2.putText(frame, 'TRI', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2, cv2.LINE_AA) elif 4