Decode base64 images using a loop - python

I have an unknown number of images which were encoded using base64. They are in the following format:
image0 = """\ iVBORw0KGgoAAAANSUhEUgAAABcAAAATCAIAAAD02QHhAAAAB3RJTUUH3gMEFjA2JHVG0AAAAe5JREFUeJztUzGr6jAYTZoWVAQRKTooOIja0SK4da6DkyCIi39AN531DzgKIoroLoiDk3ZWB3UoCiIqFDq5OBRKaXKHXOLjPnn3Xd76zpYvyTnfd3ICCSHgn8G9rf6UmieEQAgJIRjjFzfHUS4I4RdeWqRX2C78syzTYEsqgDH+lYvHGHMc93g8DoeD1+t1HMc0Tb/fr6oqlWJHKY7HYyKREAThswsIAQCc67qEEF3Xd7tdo9GYTqeWZWUyGYQQFaD6EELbtjVNq1ar2+12u90+Hg82KS8IAiFEURRFUfb7fbvdDgQCAIDZbHY+nwVBqNVqk8lkvV63Wq3RaBSNRk+nk23bsVjs5R3G2HVd13Xv93upVHIcx3Gc+XzebDY1TSsUCoSQdDrd7XYJIeVyebVakd/AQwhp59frNRKJ8DwPAFgsFj6f73a79Xq94XBYr9eXy6Xf7z+fz7IsY4xt2/Z4PMyal+GbzSYej1PucDj8fD4lSer3+8FgMJVK6bqeTCaz2Wyn0xmPx9RN5i5qtVo0IJZlybIsiiIAIJfLGYZhmmalUkEIDQaDfD6vqqokSZfLpVgshkIh9nDf54X6ZxiGKIpshC+B/GShJZpdllrXdQEACCHWNj2JMUYI/Sy77DJr/i2+Z/kbvP/T/1k+AL7rRN+R/gD6AAAAAElFTkSuQmCC """
image1 = """\ iVBORw0KGgoAAAANSUhEUgAAABcAAAATCAIAAAD02QHhAAAAB3RJTUUH3gMEFjE42tZalgAAAoRJREFUeJyNUz1PKlEQnbl3YzTYEBshodpGo62hIdgaExsLKiojP4DChD9AI50/wGggsSAhivEnYAKJ0kEAjRUaCODKx25C9t6xGFzfU3nPKe7encycPXPmLBIRAPDpuu7V1dV4PAYApZRlWQcHB36/HwC01oiIiESEiLVajYg2NjYAAAAEPxjFtm2t9cPDQzabDQQCe3t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7earUQcXl52fO8QCDwhxZmJiKl1MPDg23bSinXdQ8PD1dWVhzHCYfDJycniGjbdrVaXVpaWl9f39raisfjiNhjQUQAsCxLStloNBYWFqSUtVrNdd1yuZzNZu/v72dnZ5PJZDqdLhQKsVgMABzHISJm7rFoOYj4/v7e6XTm5+eJKBqNjo2NMfP19fXn5+fExIRlWd1ud39///j4OJfLfXx8aON7veh2iKher2vDfN9n5kqlks/ny+UyM2cymWw2WywWmfnq6ur19ZWZlVLMjPp3BqB16VVnfN+3LKvT6UxOTpq8CX5YTCURSSn10YyJuaAz/fkfd43BiCil1IEu8zzv5uamVCr1F0sp9QTpKgEjoEUBQK1Wcxxnb2/v6elJE/192RrFoh9k5kQikUgknp+fx8fHjeQB/KZFKUVEZ2dnyWQyEonEYjHd0fDbo6Anqtvtuq67trZWrVbN1w5gZEdEJIR4eXkJBoONRmNqampmZmaoKb/5Ypo6OjoSQhwcHEQikVEdDZ86w9JfM3D8Jy1mxvQziCiEMPF/aDF0Qyv78Q28N9fZLnpYLAAAAABJRU5ErkJggg== """
I can successfully decode them using:
imageToShow = base64.b64decode(image0)
stream1 = cStringIO.StringIO(imageToShow)
bmp1 = wx.ImageFromStream(stream1)
self.image_spot0.SetBitmap(wx.BitmapFromImage(bmp1))
imageToShow = base64.b64decode(image1)
stream1 = cStringIO.StringIO(imageToShow)
bmp1 = wx.ImageFromStream(stream1)
self.image_spot1.SetBitmap(wx.BitmapFromImage(bmp1))
imageToShow = base64.b64decode(image2)
stream1 = cStringIO.StringIO(imageToShow)
bmp1 = wx.ImageFromStream(stream1)
self.image_spot2.SetBitmap(wx.BitmapFromImage(bmp1))
Since there could be 3, 100, 300 or hey why not 5000 encoded images, I would like to be able to process the decoding using a loop.
When I attempted using the following code:
image_group = ['image0', 'image1', 'image2']
for img in image_group:
imageToShow = base64.b64decode(img)
I get a padding error, I assume that the data is not passing to base64.b64decode(), only the actually string "image0". Any help would be appreciated.

You mixed up variable name string literal with same value.
The solution is in writing:
image_group = ['image0', 'image1', 'image2']
You can even reduce it by combining declarations like:
image_group = [
"iVBORw0KGgoAAAANSUhEUgAAA...",
"iVBORw0KGgoAAAANSUhEUgAAA...",
"iVBORw0KGgoAAAANSUhEUgAAA..."
]

Related

Have an image link from iMDB api, how can I change it's size pyton

I am trying to work with IMDb API. My code thus far is
import http.client
import json
import requests
conn = http.client.HTTPSConnection("imdb-api.com", 443)
payload = ''
headers = {'User-agent': 'Chrome/95.0'}
conn.request("GET", "https://imdb-api.com/en/API/MostPopularMovies/<API_Key>",headers=headers)
res = conn.getresponse()
data = res.read()
convertedDict = json.loads(data.decode("utf-8"))
imagepath = r'venv/files/image.jpeg'
req = requests.get(convertedDict['items'][0]['image'], headers=headers)
with open(imagepath, 'wb') as file:
file.write(req.content)
This allows me to download the image of the first popular movie, however, the image size is really small. This is the link that I am downloading. I know that if I get rid of everything after # the image will become a lot larger. Is there a way to edit the link such that I can drop everything after # and even edit the numbers after UX with code?
Everything I try to do with string or URL operations give's me an error
https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#._V1_UX128_CR0,3,128,176_AL_.jpg
Thank you in advance
Explanation
(code example below)
Here's how to get a bigger image of the size you want. Given this URL,
https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#._V1_UX128_CR0,3,128,176_AL_.jpg
There's a substring of it:
UX128_CR0,3,128,176
This has three important parts:
The first 128 resizes the image by width, keeping ratio
The second 128 controls the container width that the image appears in
176 controls the container height that the image appears in.
So, we can view the structure like this:
UX<image_width>_CR0,3,<container_width>,<container_height>
As an example, to double the image size:
UX256_CR0,3,256,352_AL_.jpg
(Click here to see: https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#.V1_UX256_CR0,3,256,352_AL.jpg
Update: Example of how you might do it in Python.
import re
resize_factor = 2 # Image size multiple
url = "https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#._V1_UX128_CR0,3,128,176_AL_.jpg"
#
# resize_factor : Image size multiplier (e.g., resize_factor = 2 doubles the image size, positive integer only)
# url : full URL of the image
# return : string of the new URL
#
def getURL(resize_factor, url):
# Regex for pattern matching relevant parts of the URL
p = re.compile(".*UX([0-9]*)_CR0,([0-9]*),([0-9]*),([0-9]*).*")
match = p.search(url)
if match:
# Get the image dimensions from the URL
img_width = str(int(match.group(1)) * resize_factor)
container_width = str(int(match.group(3)) * resize_factor)
container_height = str(int (match.group(4)) * resize_factor)
# Change the image dimensions
result = re.sub(r"(.*UX)([0-9]*)(.*)", r"\g<1>"+ img_width +"\g<3>", url)
result = re.sub(r"(.*UX[0-9]*_CR0,[0-9]*,)([0-9]*)(.*)", r"\g<1>"+ img_width +"\g<3>", result)
result = re.sub(r"(.*UX[0-9]*_CR0,[0-9]*,[0-9]*,)([0-9]*)(.*)", r"\g<1>"+ container_height +"\g<3>", result)
return result
#
# Test
#
print (getURL(resize_factor,url))
Edit: Typo

How to convert Bytes object to _io.BytesIO python?

I am making a simple flask API for uploading an image and do some progresses then store it in the data base as binary, then i want to download it by using send_file() function but, when i am passing an image like a bytes it gives me an error:
return send_file(BytesIO.read(image.data), attachment_filename='f.jpg', as_attachment=True) TypeError: descriptor
'read' requires a '_io.BytesIO' object but received a 'bytes'
and My code for upload an image as follow:
#app.route('/upload', methods=['POST'])
def upload():
images = request.files.getlist('uploadImages')
n = 0
for image in images:
fileName = image.filename.split('.')[0]
fileFormat = image.filename.split('.')[1]
imageRead = image.read()
img = BytesIO(imageRead)
with graph.as_default():
caption = generate_caption_from_file(img)
newImage = imageDescription(name=fileName, format=fileFormat, description=caption,
data=imageRead)
db.session.add(newImage)
db.session.commit()
n = n + 1
return str(n) + ' Image has been saved successfully'
And my code for downloading an image:
#app.route('/download/<int:id>')
def download(id):
image = imageDescription.query.get_or_404(id)
return send_file(BytesIO.read(image.data), attachment_filename='f.jpg', as_attachment=True)
any one can help please???
It seems you are confused io.BytesIO. Let's look at some examples of using BytesIO.
>>> from io import BytesIO
>>> inp_b = BytesIO(b'Hello World', )
>>> inp_b
<_io.BytesIO object at 0x7ff2a71ecb30>
>>> inp.read() # read the bytes stream for first time
b'Hello World'
>>> inp.read() # now it is positioned at the end so doesn't give anything.
b''
>>> inp.seek(0) # position it back to begin
>>> BytesIO.read(inp) # This is same as above and prints bytes stream
b'Hello World'
>>> inp.seek(0)
>>> inp.read(4) # Just read upto four bytes of stream.
>>> b'Hell'
This should give you an idea of how read on BytesIO works. I think what you need to do is this.
return send_file(
BytesIO(image.data),
mimetype='image/jpg',
as_attachment=True,
attachment_filename='f.jpg'
)

Scraping all the images from a specific part of a webpage using BeautifulSoup

Object 'gallery' is what I got - how would I be able to just select the image urls without going a long way around.
Currently, I am doing the following
from bs4 import BeautifulSoup
from PIL import Image
import requests
gallery = soup.findAll(class_='gallery')
img_0 = gallery[0].find('img')
img_1 = gallery[1].find('img')
...
img_x = gallery[x].find('img')
img_url_0 = img_0['src']
img_url_1 = img_1['src']
...
img_url_x = img_x['src']
gallery_img_0 = Image.open(requests.get(img_url_0, stream = True).raw)
gallery_img_1 = Image.open(requests.get(img_url_1, stream = True).raw)
...
gallery_img_x = Image.open(requests.get(img_url_x, stream = True).raw)
where x is the length of the gallery iterable.
Perhaps a loop? :s
Thanks, CN
You can use nested loop to load all image and store them to a list. For example:
galleries = soup.findAll(class_='gallery')
all_images = []
for gallery in galleries:
for img in gallery.findAll('img'):
gallery_img = Image.open(requests.get(img['src'], stream = True).raw)
all_images.append(gallery_img)
# here, `all_images` contains all images
# ...

generating video using moviepy using image and text but getting ERROR like size = clips[0].size AttributeError: 'list' object has no attribute 'size'

import glob
import os
from natsort import natsorted
from moviepy.editor import *
base_dir = os.path.realpath("./images/")
print(base_dir)
gif_name = 'pic'
fps = 24
file_list = glob.glob('./images/*.jpg') # Get all the pngs in the current directory
file_list_sorted = natsorted(file_list,reverse=False) # Sort the images
clips = [ImageClip(m).set_duration(5)
for m in file_list_sorted]
print (clips)
text_list = ["Piggy", "Kermit", "Gonzo", "Fozzie"]
clip_list = []
for text in text_list:
try:
txt_clip = ( TextClip(text, fontsize = 70, color = 'white').set_duration(2))
clip_list.append(txt_clip)
except UnicodeEncodeError:
txt_clip = TextClip("Issue with text", fontsize = 70, color = 'white').set_duration(2)
clip_list.append(txt_clip)
print(clip_list)
final_clip = CompositeVideoClip([clips, clip_list])
final_clip.write_videofile("./video/export.mp4", fps = 24, codec = 'mpeg4')
But getting ERROR like size = clips[0].size
AttributeError: 'list' object has no attribute 'size'
i need to display image for first 15sec and after 15 sec text should be display 10 sec.
Hi thanks for posting the question. Hopefully this would be helpful.
Your main mistake concerns the following line:
final_clip = CompositeVideoClip([clips, clip_list])
CompositeVideoClip.__init__ expects a list of type Clip (CompositeVideoClip inherits the Clip class). However, in your previous lines:
print(clips)
...
print(clip_list)
so what you have effectively fed to the CompositeVideoClip.__init__ method is a nested list. So instead, you should do something like the following:
final_clip = CompositeVideoClip(clips + clip_list)
I'm sure you can come up with a more elegant solution, this is a working solution for you to start with. Do write further in case my proposal does not work.

nibabel.filebasedimages.ImageFileError: Cannot work out file type

i am getting this error when i am applying medical torch code , i know my data is tif and gif format , and i think this part " mt_datasets.SegmentationPair2D" deals just with “nii” format what i can change to make it work with other fromat than “nii”
ROOT_DIR_GMCHALLENGE = r'C:\Users~~~\eyedata\train'
mri_input_filename = os.path.join(ROOT_DIR_GMCHALLENGE,
'img')
mri_gt_filename = os.path.join(ROOT_DIR_GMCHALLENGE,
'label')
pair = mt_datasets.SegmentationPair2D(mri_input_filename, mri_gt_filename)
slice_pair = pair.get_pair_slice(0)
input_slice = slice_pair["input"]
gt_slice = slice_pair["gt"]

Categories

Resources