我正在通过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)
答案 0 :(得分:14)
另一种方式,
在读取实际文件的情况下,这将适用于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
答案 1 :(得分:11)
答案 2 :(得分:2)
我明白了:
# 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)
答案 3 :(得分:0)
(你的问题似乎被标记为objective-c但是你要求Python,所以你的例子也是如此,所以我会用它。) 我在Stack Overflow上的第一篇文章!
cv.LoadImageM方法似乎就是你要找的。 p>
http://opencv.willowgarage.com/documentation/python/reading_and_writing_images_and_video.html
使用示例: http://opencv.willowgarage.com/wiki/PythonInterface/
LoadImage(filename,iscolor = CV_LOAD_IMAGE_COLOR)→无
Loads an image from a file as an IplImage. Parameters: filename (str) – Name of file to be loaded. iscolor (int) – Specific color type of the loaded image: CV_LOAD_IMAGE_COLOR the loaded image is forced to be a 3-channel color image CV_LOAD_IMAGE_GRAYSCALE the loaded image is forced to be grayscale CV_LOAD_IMAGE_UNCHANGED the loaded image will be loaded as is.
函数cvLoadImage从指定的文件加载图像 返回指向已加载图像的指针。目前有以下文件 支持格式:
Windows bitmaps - BMP, DIB JPEG files - JPEG, JPG, JPE Portable Network Graphics - PNG Portable image format - PBM, PGM, PPM Sun rasters - SR, RAS TIFF files - TIFF, TIF
请注意,在当前实现中,alpha通道(如果有)是 从输出图像中剥离,例如, 4通道RGBA图像将 加载为RGB。
答案 4 :(得分:0)
这对我有用(这些天):
import cv2
import numpy as np
data = open('016e263c726a.raw').read()
x = np.frombuffer(data, dtype='uint8').reshape(2048,2448)
cv2.imshow('x',x); cv2.waitKey(); cv2.destroyAllWindows()
但是它会读取保存的 RAW 图片,没有任何特定格式。
答案 5 :(得分:-2)
当你必须从文件加载时,这个简单的解决方案完成了这项工作(使用opencv-python-3.2.0.6
测试):
import cv2
img = cv2.imread(somefile)