问题描述
我在 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,0),2)
cv2.imshow("window",frame1)
frame1 = frame2
frame2 = wincap.get_screenshot()
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
欢迎任何帮助或建议。谢谢
解决方法
这个功能可以帮到你。它计算轮廓的边界框区域并从图像中裁剪它。
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