如何从python opencv中的数组读取原始png?

2024-03-12

我正在通过 TCP 将 png 图像从 iPhone 传输到 MacBook。 MacBook 代码来自http://docs.python.org/library/socketserver.html#requesthandler-objects 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),它可能是最好的解决方案。

但是,因为这个问题对于最新版本的用户来说同样有趣,所以我建议以下解决方案。下面的示例代码可能比公认的解决方案更好,因为:

  1. 它与较新的 OpenCV python API(cv2 与 cv)兼容。该解决方案在opencv 3.0和python 3.0下进行了测试。我相信 opencv 2.x 和/或 python 2.7x 只需要进行一些简单的修改。
  2. 进口量减少。这一切都可以直接用numpy和opencv来完成,不需要StringIO和PIL。

以下是我如何创建直接从文件对象或从文件对象读取的字节缓冲区解码的 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='...' 标志。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从python opencv中的数组读取原始png? 的相关文章

随机推荐