Python OpenCV 从字节字符串加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17170752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python OpenCV load image from byte string
提问by featureoffuture
I'm trying to load image from string like as PHP function imagecreatefromstring
我正在尝试像 PHP 函数一样从字符串加载图像 imagecreatefromstring
How can I do that?
我怎样才能做到这一点?
I have MySQL blob field image. I'm using MySQLdband don't want create temporary file for working with images in PyOpenCV.
我有 MySQL blob 字段图像。我正在使用MySQLdb并且不想创建临时文件来处理 PyOpenCV 中的图像。
NOTE: need cv (not cv2) wrapper function
注意:需要 cv(不是 cv2)包装函数
采纳答案by jabaldonedo
This is what I normally use to convert images stored in database to OpenCV images in Python.
这是我通常用来将存储在数据库中的图像转换为 Python 中的 OpenCV 图像的方法。
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)
I have added the conversion from numpy.ndarrayto cv2.cv.iplimage, so the script above will print:
我已经添加了从numpy.ndarrayto的转换cv2.cv.iplimage,所以上面的脚本将打印:
<type 'str'>
<type 'numpy.ndarray'>
<type 'cv2.cv.iplimage'>
回答by Alexandre Mazel
I've try to use this code to create an opencv from a string containing a raw buffer (plain pixel data) and it doesn't work in that peculiar case.
我尝试使用此代码从包含原始缓冲区(纯像素数据)的字符串创建一个 opencv,但在这种特殊情况下它不起作用。
So here's how to do that for this kind of data:
所以这里是如何为这种数据做到这一点:
image = np.fromstring(im_str, np.uint8).reshape( h, w, nb_planes )
(but yes you need to know your image properties)
(但是是的,您需要知道您的图像属性)
if your B and G channel is permuted, here's how to fix it:
如果您的 B 和 G 通道被置换,以下是修复它的方法:
image = cv2.cvtColor(image, cv2.cv.CV_BGR2RGB)
回答by Anugraha Sinha
I think thisanswer provided on thisstackoverflow question is a better answer for this question.
我认为thisstackoverflow question上提供的这个答案是这个问题的更好答案。
Quoting details (borrowed from @lamhoangtung from above linked answer)
引用细节(从上面链接的答案中借用@lamhoangtung)
import base64
import json
import cv2
import numpy as np
response = json.loads(open('./0.json', 'r').read())
string = response['img']
jpg_original = base64.b64decode(string)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img = cv2.imdecode(jpg_as_np, flags=1)
cv2.imwrite('./0.jpg', img)

