Warm tip: This article is reproduced from serverfault.com, please click

python-如何使用从网络摄像头捕获的图像/帧在同一脚本中进行后期处理

(python - How to use an image(s)/frame(s) captured from a webcam to post process in the same script)

发布于 2021-01-19 23:04:46

我基本上有一个运动检测器,它使用我的网络摄像头工作,它将第一帧作为“dart_0”,然后在检测到运动时将一帧作为“dart_1”。

我希望能够保存这些图像,以便我可以立即在同一个 python 文件/脚本中对它们进行后期处理。

目前它将它们保存为 .png 文件,但在 while 循环之后,它不会让我读取新创建的文件。它只让我在一个单独的脚本中执行此操作,这不是我想要的。

我要问的是,是否有一种方法可以在 while 循环中断时将图像本地保存在脚本中,我可以在获得它们后立即处理这些图像。

到目前为止,这是我的代码,它按我的意愿完美运行,但是在 while 循环中断之后,我无法使用我刚刚创建的图像。

import cv2

first_frame = None
video = cv2.VideoCapture(0, cv2.CAP_DSHOW)
video.set(cv2.CAP_PROP_BUFFERSIZE, 0)

img_counter = 1

throw_count = 1
throw_limit = 5

while throw_count < throw_limit:

    status, frame = video.read()
    #print(status)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)

    if first_frame is None:
        first_frame = gray
        cv2.imwrite(filename='dart_0.png', img=frame)
        print("Empty Picture Captured")
        continue

    #cv2.imshow("Frame", frame)
    #cv2.imshow("Capturing", gray)

    delta_frame = cv2.absdiff(first_frame, gray)
    thresh_delta = cv2.threshold(delta_frame, 30, 255, cv2.THRESH_BINARY)[1]
    thresh_delta = cv2.dilate(thresh_delta, None, iterations=0)
    contours, res = cv2.findContours(thresh_delta.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    #cv2.imshow("Delta", delta_frame)
    #cv2.imshow("Thresh", thresh_delta)

    for contour in contours:
        if cv2.contourArea(contour) > 100:
            #(x, y, w, h) = cv2.boundingRect(contour)
            #cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
            throw_count += 1
            cv2.imwrite(filename='dart_1.png', img=frame)
            print("Image Saved")

print("Loop Ended")
Questioner
JT11234567
Viewed
11
Carlos Melus 2021-01-20 11:50:00

如果你在循环中使用的最后一张图像是你想要保留以供进一步分析的图像,请将其保存在变量 ( selected_frame) 中,例如在将其保存到磁盘之前:

for contour in contours:
    if cv2.contourArea(contour) > 100:
        throw_count += 1
        selected_frame = frame.copy()
        cv2.imwrite(filename='dart_1.png', img=frame)
        print("Image Saved")

第一帧已经保存在变量中first_frame,可以在后续代码中使用。