Python opencv运动检测将轮廓结果提取到文件或函数

2024-10-01 04:57:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在OpenCV中有运动跟踪功能,但我想让python在运动检测中提取轮廓内的任何东西的图像,以便将来在程序中使用或作为图像写入

迄今为止的代码:

import cv2
import numpy as np

from windowcapture import WindowCapture

wincap = WindowCapture('your window here')

frame1 = wincap.get_screenshot()
frame2 = wincap.get_screenshot()

while(True):

    diff = cv2.absdiff(frame1, frame2)
    gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None, iterations=3)
    contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2)

    cv2.imshow("window", frame1)
    frame1 = frame2
    frame2 = wincap.get_screenshot()

    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

欢迎提供任何帮助或建议。谢谢


Tags: 图像importgetdiffwindowcv2screenshotgray
1条回答
网友
1楼 · 发布于 2024-10-01 04:57:49

这个功能可以帮助你。它计算轮廓的边界框区域,并从图像中裁剪轮廓

def get_sub_images(image, contours):
    """
    Crop images according to the contour bounding boxes and return them in a
    list.

    Args:
        image: numpy.ndarray
        contours: list

    Returns:
        list
    """
    sub_images = []
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        sub_image = image[slice(y, y+h), slice(x, x+w)]
        sub_images.append(sub_image)
    return sub_images

相关问题 更多 >