我正在通过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)发布于 2012-07-22 23:17:56
我想通了:
# Read rawImage from a file, but in reality will have it from TCPServer
f = open('frame.png', "rb")
rawImage = f.read()
f.close()
# Convert rawImage to Mat
pilImage = Image.open(StringIO(rawImage));
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)
#show it
cv.NamedWindow('display')
cv.MoveWindow('display', 10, 10)
cv.ShowImage('display', matImage)
cv. WaitKey(0) 发布于 2015-12-27 05:09:41
@Andy Rosenblum的作品,如果使用过时的cv python API (vs. 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位图像,但如果不是,您可以使用dtype='...‘np.fromstring中的标志。
发布于 2013-07-09 19:50:47
另一种方式,
此外,在读取实际文件的情况下,这将适用于unicode路径(在windows上测试)
with open(image_full_path, 'rb') as img_stream:
file_bytes = numpy.asarray(bytearray(img_stream.read()), dtype=numpy.uint8)
img_data_ndarray = cv2.imdecode(file_bytes, cv2.CV_LOAD_IMAGE_UNCHANGED)
img_data_cvmat = cv.fromarray(img_data_ndarray) # convert to old cvmat if neededhttps://stackoverflow.com/questions/11552926
复制相似问题