And*_*lum 12 python png opencv
我正在通过tcp将我的iPhone中的png图像传输到我的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)
Run Code Online (Sandbox Code Playgroud)
Noa*_*fen 15
其他方式,
在读取实际文件的情况下,这将适用于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 needed
Run Code Online (Sandbox Code Playgroud)
svo*_*ara 13
@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)
Run Code Online (Sandbox Code Playgroud)
请注意,在opencv 3.0中,各种常量/标志的命名约定已更改,因此如果使用opencv 2.x,则需要更改标志cv2.IMREAD_UNCHANGED.此代码示例还假定您正在加载标准的8位图像,但如果没有,则可以使用np.fromstring中的dtype ='...'标志.
我想到了:
# 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)
Run Code Online (Sandbox Code Playgroud)