作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在通过 tcp 将 png 图像从我的 iPhone 流式传输到我的 MacBook。 MacBook代码来自http://docs.python.org/library/socketserver.html#requesthandler-objects .如何转换图像以供 OpenCV 使用?选择 png 是因为它们效率高,但也可以使用其他格式。
我写了一个测试程序,从一个文件中读取 rawImage,但不确定如何转换它:
# Read rawImage from a file, but in reality will have it from TCPServer
f = open('frame.png', "rb")
rawImage = f.read()
f.close()
# Not sure how to convert rawImage
npImage = np.array(rawImage)
matImage = cv2.imdecode(rawImage, 1)
#show it
cv.NamedWindow('display')
cv.MoveWindow('display', 10, 10)
cv.ShowImage('display', matImage)
cv. WaitKey(0)
最佳答案
@Andy Rosenblum 的作品,如果使用过时的 cv python API(相对于 cv2),它可能是最佳解决方案。
但是,因为这个问题对最新版本的用户来说同样有趣,所以我建议采用以下解决方案。下面的示例代码可能比公认的解决方案更好,因为:
以下是我如何创建直接从文件对象或从文件对象读取的字节缓冲区解码的 opencv 图像。
import cv2
import numpy as np
#read the data from the file
with open(somefile, 'rb') as infile:
buf = infile.read()
#use numpy to construct an array from the bytes
x = np.fromstring(buf, dtype='uint8')
#decode the array into an image
img = cv2.imdecode(x, cv2.IMREAD_UNCHANGED)
#show it
cv2.imshow("some window", img)
cv2.waitKey(0)
请注意,在 opencv 3.0 中,各种常量/标志的命名约定发生了变化,因此如果使用 opencv 2.x,则需要更改标志 cv2.IMREAD_UNCHANGED。此代码示例还假设您正在加载标准的 8 位图像,但如果不是,您可以使用 np.fromstring 中的 dtype='...' 标志。
关于python - 如何从 python opencv 中的数组中读取原始 png?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11552926/
我是一名优秀的程序员,十分优秀!