Answer a question

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?

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....

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

Answers

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

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)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐