致力于从整个网页屏幕截图中提取托管 Youtube 视频元素的矩形。 我正在努力寻找任何能够在不同视频和页面形式因素上准确工作的解决方案。
这是我找到的最有希望的解决方案:
阈值
查找轮廓
查看最大边界矩形
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
gray = clahe(gray, 5, (3, 3))
img_blur = cv2.blur(gray, (9, 9))
img_th = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 2)
contours, hierarchy = cv2.findContours(img_th,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
我想要从图像中看到的是托管视频内容的中央大蓝色矩形。 默认情况下,显然没有显示在检测到的轮廓中。
也尝试过 Canny 而不是阈值化,但效果不佳。 关于我可以采取什么方法来解决这个问题有什么建议吗? (关于如何处理检测到的轮廓或可能生成一组经过更多过滤的轮廓)
我觉得这个问题应该比许多涉及现实世界图像的图像处理任务更简单,因为这里的对象具有完美的边界。
要从网页截图中准确提取托管 YouTube 视频元素的矩形,您可以尝试以下方法:
预处理:
将图像转换为灰度。 应用直方图均衡化或 CLAHE 来增强对比度。 模糊图像以减少噪声。 边缘检测:
使用 Canny 边缘检测来识别图像中的边缘。 轮廓检测:
在边缘检测图像中查找轮廓。 根据大小和纵横比过滤轮廓,以删除小的和不相关的轮廓。 矩形提取:
识别可能代表视频元素的最大矩形轮廓。 通过确保矩形位于图像的中心并具有与视频播放器一致的尺寸来进一步细化矩形。
你的代码看起来像这样:
import cv2
import numpy as np
# Load the image
image = cv2.imread('webpage_screenshot.png')
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply CLAHE for contrast enhancement
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
gray = clahe.apply(gray)
# Blur the image
blurred = cv2.blur(gray, (9, 9))
# Edge detection using Canny
edges = cv2.Canny(blurred, 30, 150)
# Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Filter contours based on size and aspect ratio
filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 1000]
filtered_contours = [cnt for cnt in filtered_contours if cv2.arcLength(cnt, True) > 100]
# Sort contours by area in descending order
filtered_contours = sorted(filtered_contours, key=cv2.contourArea, reverse=True)
# Extract the largest rectangle
if filtered_contours:
x, y, w, h = cv2.boundingRect(filtered_contours[0])
# Draw the rectangle on the original image
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the result
cv2.imshow('Rectangle', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("No rectangle found.")