python - 将 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.ndarray
of转换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)
推荐阅读
- visual-studio-code - 错误代码尝试从不存在的源复制
- github - 恢复对主分支 git 所做的更改
- node.js - 如何修复未定义且 arg 未读取拆分中的正确行?
- swift - 在 SwiftUI 视图中更改 UIColor 的不透明度
- python - 如何在 Azure ML 上部署 EfficientNet?
- python - 根据键值聚合列表中的字典
- php - chmod() 导致 Whmcs 更新失败:不允许操作
- react-native - 如何在文本字段中添加动态 onfocus / input ref?
- powerbi - 对同一变量使用多个过滤器的 Distinctcount
- node.js - 节点路由间歇性工作