Convert numpy array to base64 - python

I want to convert frame from a video file to base64 without save in directory.
I use: img = frame.copy() to take a frame from my video and it return a numpy array.
How can i convert it into base64 to store in database and display it into web.
Thanks for your help.

The following code should work - note you'll have to switch around the format as needed, and the corresponding base64 string. In this example I've used PNG.
from PIL import Image
from io import BytesIO
import base64
data = frame.copy()
image_out = Image.fromarray(data)
buffer = BytesIO()
image_out.save(buffer, format="PNG")
base64_str = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode("utf-8")
Output:
>>> base64_str
`data:image/png;base64,iVBORw...`

Related

Display image in ".kv" file without saving the image

How to display the QrCode in "kv" file as decoded?
I want to display the image without saving it. I figured out that I can stored as binary, but I don't know how to decoded into "kv" file. I attempted to decoded as following line, but it didn't work:
source: base64.b64encode(root.img_data1).decode('utf-8')
import wifi_qrcode_generator as qr
from io import BytesIO
g = g = qr.wifi_qrcode(ssid_wifi,"False","WPA",passd)
# Save QR code image to BytesIO object
img_file = BytesIO()
g.save(img_file, format='PNG')
img_file.seek(0)
# Encode image data to base64
import base64
img_base64 = base64.b64encode(img_file.read()).decode('utf-8')
# Set img_data to the base64 encoded image data
img_data = base64.b64decode(img_base64)

Converting Image to Bytearray with Python

I want to convert Image file to Bytearray. I extracted image from pdf file with minecart lib, but I cant find a way to convert it to bytearray. This is my code:
import minecart
from PIL import Image
import io
pdffile = open('sample6.pdf', 'rb')
doc = minecart.Document(pdffile)
for page in doc.iter_pages():
print(page)
img = page.images[0].as_pil()
print(img) # <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1641x2320 at 0x7FBDF02E6A00>
print(type(img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
I have tried to use bytearray(img) but It does not work.
Do you have solution for this (solution that does not consume to much time)?
Create io.BytesIO buffer and write to it using PIL.Image.save. Set appropriate quality and other parameters as per requirement.
import io
from PIL import Image
def convert_pil_image_to_byte_array(img):
img_byte_array = io.BytesIO()
img.save(img_byte_array, format='JPEG', subsampling=0, quality=100)
img_byte_array = img_byte_array.getvalue()
return img_byte_array
References:
Why is the quality of JPEG images produced by PIL so poor?

How to resize base64 encoded image in python

I want resize base64 encoded image in python.I searched I could not find. I used Pillow package to do it. However, Pillow has no such kind of feature .
This code does the job (Python 3):
import io
import base64
from PIL import Image
base64_str = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
buffer = io.BytesIO()
imgdata = base64.b64decode(base64_str)
img = Image.open(io.BytesIO(imgdata))
new_img = img.resize((2, 2)) # x, y
new_img.save(buffer, format="PNG")
img_b64 = base64.b64encode(buffer.getvalue())
print(str(img_b64)[2:-1])
EDIT: Reducing the size of a base64 image does not imply reducing the file size.

Flask to Numpy Image Conversion

I have been trying to send an image over javascript to a Flask server to draw bounding boxes on coordinates I received from my own API. How might I convert this to a numpy array?
I was thinking of using the cv2.imdecode feature, but I don't want to download that huge file on my server. Here is an example of the input string src i am sending to flask:
data:image/jpeg;base64,IMGDATA HERE
I believe that this string is base64 encoded, but I am not sure how to make this conversion in python.
I have done something similar to this. If you have your url, then you first have to decode the IMGDATA part of the src string, which is base64 encoded. So first you need to separate IMGDATA from the inputstring. This can be done using:
import base64
imgdata = imgsrcstring.split(',')[1]
decoded = base64.b64decode(imgdata)
Then you can use the PIL Libarary to convert the Bytes representation of the string to an image, which can then be converted to a numpy array:
from PIL import Image
from io import BytesIO
img = np.array(Image.open(BytesIO(decoded)))
def upload_file():
if request.method == 'POST':
f = request.files['file'].read()
# print(f)
npimg = np.fromstring(f,np.uint8)
img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
img = Image.fromarray(img.astype("uint8"))
#do anything with image here
rawBytes = io.BytesIO()
img.save(rawBytes, "JPEG")
rawBytes.seek(0)
img_base64 = base64.b64encode(rawBytes.getvalue()).decode('ascii')
mime = "image/jpeg"
uri = "data:%s;base64,%s"%(mime, img_base64)
return render_template("./template/output.html",image=uri)
this will read image from the javascript code and after you have performed operations will return image which can be passed in HTML page given you assign placeholder for the image on the page.

Read a base 64 encoded image from memory using OpenCv python library

I'm working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri's of the canvas and want to use it to do something like this:
cv2.imshow('image',img)
The data URI looks something like this:
data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7
So, for clarity I've shown what the image looks like so the base64 string is not broken.
<img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7">
The official doc says, that imread accepts a file path as the argument. From this SO answer, if I do something like:
import base64
imgdata = base64.b64decode(imgstring) #I use imgdata as this variable itself in references below
filename = 'some_image.jpg'
with open(filename, 'wb') as f:
f.write(imgdata)
The above code snippet works and the image file gets generated properly. However I don't think so many File IO operations are feasible considering I'd be doing this for every frame of the stream. I want to be able to read the image into the memory directly creating the img object.
I have tried two solutions that seem to be working for some people.
Using PIL reference:
pilImage = Image.open(StringIO(imgdata))
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)
I get cv not defined as I have openCV3 installed which is available to me as cv2 module. I tried img = cv2.imdecode(npImage,0), this returns nothing.
Getting the bytes from decoded string and converting it into an numpy array of sorts
file_bytes = numpy.asarray(bytearray(imgdata), dtype=numpy.uint8)
img = cv2.imdecode(file_bytes, 0) #Here as well I get returned nothing
The documentation doesn't really mention what the imdecode function returns. However, from the errors that I encountered, I guess it is expecting a numpy array or a scalar as the first argument. How do I get a handle on that image in memory so that I can do cv2.imshow('image',img) and all kinds of cool stuff thereafter.
I hope I was able to make myself clear.
This is my solution for python 3.7 and without using PIL
import base64
def readb64(uri):
encoded_data = uri.split(',')[1]
nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
i hope that this solutions works for all
This worked for me on python 2, and doesn't require PIL/pillow or any other dependencies (except cv2):
Edit: for python3 use base64.b64decode(encoded_data) to decode instead.
import cv2
import numpy as np
def data_uri_to_cv2_img(uri):
encoded_data = uri.split(',')[1]
nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
data_uri = "data:image/jpeg;base64,/9j/4AAQ..."
img = data_uri_to_cv2_img(data_uri)
cv2.imshow(img)
You can just use both cv2 and pillow like this:
import base64
from PIL import Image
import cv2
from StringIO import StringIO
import numpy as np
def readb64(base64_string):
sbuf = StringIO()
sbuf.write(base64.b64decode(base64_string))
pimg = Image.open(sbuf)
return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)
cvimg = readb64('R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7')
cv2.imshow(cvimg)
I found this simple solution.
import cv2
import numpy as np
import base64
image = "" # raw data with base64 encoding
decoded_data = base64.b64decode(image)
np_data = np.fromstring(decoded_data,np.uint8)
img = cv2.imdecode(np_data,cv2.IMREAD_UNCHANGED)
cv2.imshow("test", img)
cv2.waitKey(0)
Source : https://gist.github.com/HoweChen/7cdd09b08147133d8e1fbe9b52c24768

Categories