将base64字符串转换为与OpenCV兼容的映像 [英] Convert base64 String to an Image that's compatible with OpenCV

查看:101
本文介绍了将base64字符串转换为与OpenCV兼容的映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JPEG的base64表示形式转换为可与OpenCV一起使用的图像.问题是我希望能够做到这一点而不必实际保存照片(我希望照片保留在内存中).有没有更新的方式来做到这一点?

I'm trying to convert a base64 representation of a JPEG to an image that can be used with OpenCV. The catch is that I'd like to be able to do this without having to physically save the photo (I'd like it to remain in memory). Is there an updated way of accomplishing this?

我正在使用python 3.6.2和OpenCV 3.3

I'm using python 3.6.2 and OpenCV 3.3

这是我要转换的输入类型的部分示例:

Here is a partial example of the type of input I'm trying to convert:

/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAA ....

/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAA....

我已经尝试了这些问题提供的解决方案,但是仍然收到相同的内置操作的错误参数类型"错误:

I've already tried the solutions provided by these questions, but keep getting the same "bad argument type for built-in operation" error:

  • Read a base 64 encoded image from memory using OpenCv python library
  • How to decode jpg image from memory?
  • Python: Alternate way to covert from base64 string to opencv

推荐答案

我已经在这个问题上苦苦挣扎了一段时间,当然,一旦我发布了一个问题,我就会解决.

I've been struggling with this issue for a while now and of course, once I post a question - I figure it out.

对于我的特定用例,我需要先将字符串转换为PIL图像以在其他函数中使用,然后再将其转换为numpy数组以在OpenCV中使用.您可能会想,为什么要转换为RGB?".之所以添加它,是因为从PIL图像-> Numpy数组转换时,OpenCV的图像默认为BGR.

For my particular use case, I needed to convert the string into a PIL Image to use in another function before converting it to a numpy array to use in OpenCV. You may be thinking, "why convert to RGB?". I added this in because when converting from PIL Image -> Numpy array, OpenCV defaults to BGR for its images.

无论如何,这是我的两个助手功能,可以解决我自己的问题:

Anyways, here's my two helper functions which solved my own question:

import io
import cv2
import base64 
import numpy as np
from PIL import Image

# Take in base64 string and return PIL image
def stringToImage(base64_string):
    imgdata = base64.b64decode(base64_string)
    return Image.open(io.BytesIO(imgdata))

# convert PIL Image to an RGB image( technically a numpy array ) that's compatible with opencv
def toRGB(image):
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

这篇关于将base64字符串转换为与OpenCV兼容的映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆