gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:16:30 24 4
gpt4 key购买 nike

我正在通过 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),它可能是最佳解决方案。

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

  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='...' 标志。

关于python - 如何从 python opencv 中的数组中读取原始 png?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11552926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com