2013-06-18 72 views
17

的Python OpenCV的负荷的形象,我试图加载从字符串图像等作为PHP函数imagecreatefromstring从字节串

我怎么能这样做?

我有MySQL blob字段图像。我正在使用MySQLdb并且不想创建用于在PyOpenCV中处理图像的临时文件。

注:需要CV(不CV2)包装函数

回答

45

这是我通常使用转换存储在数据库中的图像OpenCV的Python中的图像。

import numpy as np 
import cv2 
from cv2 import cv 

# Load image as string from file/database 
fd = open('foo.jpg') 
img_str = fd.read() 
fd.close() 

# CV2 
nparr = np.fromstring(img_str, np.uint8) 
img_np = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR) # cv2.IMREAD_COLOR in OpenCV 3.1 

# CV 
img_ipl = cv.CreateImageHeader((img_np.shape[1], img_np.shape[0]), cv.IPL_DEPTH_8U, 3) 
cv.SetData(img_ipl, img_np.tostring(), img_np.dtype.itemsize * 3 * img_np.shape[1]) 

# check types 
print type(img_str) 
print type(img_np) 
print type(img_ipl) 

我已经添加了从numpy.ndarraycv2.cv.iplimage转换,所以上面的脚本会打印:

<type 'str'> 
<type 'numpy.ndarray'> 
<type 'cv2.cv.iplimage'> 
+0

哇!谢谢!我在谷歌搜索,但没有发现:) – featureoffuture

+0

不客气!记得upvote /接受答案,如果你觉得它有用:) – jabaldonedo

+0

现在我不能,但是当我可以upvote那 – featureoffuture

2

我已经尝试使用此代码从包含原始缓冲区的字符串创建的OpenCV (普通像素数据),并不适用于这种特殊情况。

因此,这里是如何做到这一点对于这种数据:

image = np.fromstring(im_str, np.uint8).reshape(h, w, nb_planes) 

(但是是你需要知道你的图像属性)

如果你的B和G通道排列,这里是如何修复它:

image = cv2.cvtColor(image, cv2.cv.CV_BGR2RGB)