【问题标题】:How to get each frame as an image from a cv2.VideoCapture in python如何从 python 中的 cv2.VideoCapture 获取每一帧作为图像
【发布时间】:2020-09-20 19:10:25
【问题描述】:

我想从视频中获取每一帧作为图像。其背景如下。我写了一个能够识别手势的神经网络。现在我想启动一个视频流,其中流的每个图像/帧都通过神经网络。为了适应我的神经网络,我想渲染每一帧并将图像缩小到 28*28 像素。最后它应该看起来像这样:https://www.youtube.com/watch?v=JfSao30fMxY 我在网上搜索并发现我可以使用 cv2.VideoCapture 来获取流。但是我怎样才能选择框架的每个图像,渲染它并将结果打印回屏幕上。到目前为止,我的代码看起来像这样:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Todo: each Frame/Image from the video should be saved as a variable and open imageToLabel()
# Todo: before the image is handed to the method, it needs to be translated into a 28*28 np Array
# Todo: the returned Label should be printed onto the video (otherwise it can be )

i = 0
while (True):
    # Capture frame-by-frame
    # Load model once and pass it as an parameter

    ret, frame = cap.read()
    i += 1

    image = cv2.imwrite('database/{index}.png'.format(index=i), frame)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRAY)

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

def imageToLabel(imgArr, checkpointLoad):
    new_model = tf.keras.models.load_model(checkpointLoad)
    imgArrNew = imgArr.reshape(1, 28, 28, 1) / 255
    prediction = new_model.predict(imgArrNew)
    label = np.argmax(prediction)
    return label

【问题讨论】:

  • 添加有关模型的更多详细信息。
  • edit问题直接在那里显示代码。
  • 嘿@ZabirAlNazi 谢谢你的快速回答。 NN不是这个问题的重点。我现在添加了用于NN的方法。它通过 checkpointLoad 加载模型。然后它返回一个标签。抱歉,我是 StackOverflow 的新手。还不知道如何正确评论:D
  • @Yunnosch 是的,我做到了。我在代码末尾添加了方法。

标签: python image-processing conv-neural-network video-capture cv2


【解决方案1】:

frame 是您从流中获得的 RGB 图像。 gray 是灰度转换后的图像。 我想您的网络由于其形状而采用灰度图像。因此,您需要先将图像大小调整为 (28,28),然后将其传递给您的 imageToLabel 函数

resizedImg = cv2.resize(gray,(28,28))
label = imageToLabel(resizedImg,yourModel)

既然您知道预测,您可以在frame 上使用例如cv2.putText() 然后绘制它返回的帧而不是 frame

编辑

如果你想为你的网络使用图像的一部分,你可以像这样对图像进行切片:

slicedImg = gray[50:150,50:150]
resizedImg = cv2.resize(slicedImg,(28,28))
label = imageToLabel(resizedImg,yourModel)

如果您对 python 中的索引不太熟悉,您可能想看看this

此外,如果您希望它看起来像链接视频中的那样,您可以从例如绘制一个矩形。 (50,50) 到 (150,150) 即为绿色 (0,255,0)

cv2.rectangle(frame,(50,50),(150,150),(0,255,0))

【讨论】:

  • 感谢您的快速答复。我现在已经实现了你的代码。我唯一的问题是我只想要帧的一部分(例如,y 轴上 50 到 150 的像素和 X 轴上 50 到 150 的像素。)同样在我链接的 YouTube 视频中我的问题,你对我有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 2014-05-07
相关资源
最近更新 更多