将dtypeuint8的Numpy ndarray转换为OpenCV可读图像

问题描述

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

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

这是我当前的代码:

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.ndarray dtype中的uint8转换为OpenCV支持的图像?

解决方法

所以原因非常简单。.D3DShot捕获需要一些延迟(我将其设置为100 ms)来初始化,并且数组最终不为空并成功传递给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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...