首页 > 解决方案 > 将 dtype (uint8) 的 Numpy ndarray 转换为 OpenCV 可读图像

问题描述

长话短说 - 我正在学习如何使用这个D3DShot (Windows 桌面复制 API 的 Python 实现)库进行简单的屏幕捕获,并将捕获的数据直接传递给OpenCV

捕获的数据具有范围内np.ndarray的值。我在 Stack Overflow 和其他网站上尝试了多个建议,但无法解决这个问题,并且不断遇到错误。dtype uint8(0, 255)

这是我当前的代码:

import d3dshot
import cv2

# D3D init
d = d3dshot.create(capture_output="numpy", frame_buffer_size=60)

# Choose display
for i, display in enumerate(d.displays):
    current_display = display
    print('[' + str(i+1) + '] ' + display.name + '\n')

# Set display
current_display.i = int(input("Select display by nr.: ")) - 1
d.display = d.displays[current_display.i]
print('\nYou\'ve selected [' + str(current_display.i) + '] ' + current_display.name)

# Start capturing
d.capture(target_fps=10,)

# Send frame to opencv
while True:
    #Displayed the image
    img = d.get_latest_frame()

    #Dump it like it's hot
    print(img.shape, img.dtype)
    """
    Here we will convert from np.ndarray of dtype uint8 to opencv supported img
    """
    # Pass img to Open CV
    cv2.imshow("Test Window", img)
    cv2.waitKey(0)

转储返回:

Traceback (most recent call last):
  File ".\capture.py", line 26, in <module>
    print(img.shape, img.dtype)
AttributeError: 'NoneType' object has no attribute 'shape'

我的问题当然是如何从np.ndarrayof转换dtype uint8为 OpenCV 支持的图像?

标签: pythonwindowsnumpyopencvdirect3d

解决方案


所以原因很简单.. D3DShot 捕获需要一些延迟(我将其设置为100ms)来初始化,并且数组最终不为空并成功传递给 OpenCV。这是更新的代码:

import d3dshot
import cv2
import time

# D3D init
d = d3dshot.create(capture_output="numpy", frame_buffer_size=60)

# Choose display
for i, display in enumerate(d.displays):
    current_display = display
    print('[' + str(i+1) + '] ' + display.name + '\n')

# Set display
current_display.i = int(input("Select display by nr.: ")) - 1
d.display = d.displays[current_display.i]
print('\nYou\'ve selected [' + str(current_display.i) + '] ' + current_display.name)

# Start capturing
d.capture(target_fps=60)
time.sleep(0.1)

# Send frame to opencv
while True:
    #Displayed the image
    img = d.get_latest_frame()

    #Dump it like it's hot
    print(img.shape, img.dtype)

    # Send to Open CV
    cv2.imshow("Test Window", img)
    cv2.waitKey(1)

推荐阅读