How can I download an image that has no source (local image) - python

So I understand how I can download images from the web, in which they have an 'src' but now I am trying to access images that I have already downloaded on my computer, making changes to it, and then downloading it to my computer again.
from PIL import Image
redish = Image.open('gradient_red.jpg')
check_pics = open('pictures','wb')
check_pics.write(redish)
check_pics.close()
I tried doing the same thing as one would download images with an 'src', but it does not work because the object is not a 'byte-like object'

So I just found out that PIL library has a method called 'save'. I just had to do this.
from PIL import Image
redish = Image.open('gradient_red.jpg')
redish.save('test.jpg')
Thank you all for helping

Related

How do I mount one Google Drive folder with images only onto Google Colab and iterate through it?

I have a folder of images I extracted for a computer-vision project, but don't know how to mount it onto Google Colab and iterate through the folder. I have a function I need to apply to each image inside the folder, but don't know how to get the images.
I've tried looking for resources but haven't found anything helpful to my situation, because most of them were for unzipping files that were not images. Can you please help me out? Thank you.
You can use the OpenCV library for this.
from google.colab import drive
import os
import cv2
First you need to change the current working directory to your image folder directory.
os.chdir("/content/drive/MyDrive/yourfolder")
You can iterate through every image, apply your function to them and save the final version like this:
for file in os.listdir():
img = cv2.imread(file)
result = myfunction(img)
cv2.imwrite(file, result)

Python crashing while opening a image

I am getting an image using an API call and eventually need to put the image into a PDF document using ReportLab. Python was crashing without any error messages when I tried canvas.drawImage method in ReportLab. In order to isolate the issue, I just tried opening the image using the Image class and Python still crashes. I can open the image manually using paint and the code does not error out when using other images, leading me to believe I am missing something while converting the binary to the image. I cannot share the images or the API. The definition of the result from the API is as follows.
<GetImageResponse xmlns="http://tempuri.org/">
<GetImageResult>base64Binary</GetImageResult>
<errorMessages>string</errorMessages>
</GetImageResponse>
'''
from zeep import Client
import base64
from PIL import Image, ImageTk
client=Client(wsdl='******.asmx?wsdl')
imgService=client.service.GetImage("***",****, "***********")
imgFile="imageTest.png"
base64_bytes = base64.b64encode(imgService.GetImageResult)
with open(imgFile, "wb") as fh:
fh.write(base64.decodebytes(base64_bytes))
image = Image.open(imgFile)
image.show()
'''
Can someone point me where I need to look? Thanks in advance for any pointers.

How to read an image from a URL in Colab?

I have seen so many different threads about this topic but none of their solutions seems to work for me. I've tried several ways of reading an image from my Drive into Colab using its URL, with no success. I want to read it using its URL rather than mounting my Drive and using directories because multiple people share this Colab, and their directory to the image might not be the same as mine.
The first attempt comes from a popular thread on this issue: How do I read image data from a URL in Python?
from PIL import Image
import requests
url = 'https://drive.google.com/file/d/1z33YPsoMe0lSNNa2XWa0tiK2571j2tFu/view?usp=sharing'
im = Image.open(requests.get(url).raw) # apparently no need for bytes wrapping in new Python versions
im = Image.open(requests.get(url, stream=True).raw) # also does not work
The error I got was UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f0189569770>
Then I tried:
from skimage import io
io.imshow(io.imread(url))
Which returned ValueError: Could not find a format to read the specified file in mode 'i'. Feeling very lost because all these approaches seem to work for everyone else. Would appreciate any feedback.
Using gdown to read an image from Google Drive into Colab.
If you have your image in your Google Drive and you are using colab.research.google.com, then you can follow these steps:
pip install gdown
Obtaining the share link from your image (remember to set the option "Share to anyone with the link"). For an example:
# https://drive.google.com/file/d/1WG3DGKAo8JEG4htBSBhIIVqhn6D2YPZ/view?usp=sharing
Extract the id of the share link from the URL 1WG3DGKAo8JEG4htBSBhIIVqhn6D2YPZ.
Download the image in the folder content of a particular user who has access to this Colab:
!gdown --id '1WG3DGKAo8JEG4htBSBhIIVqhn6D2YPZ' --output bird1.jpp
Read the image file from the folder content
from PIL import Image
im = Image.open("../content/bird1.jpg")
im

Display an image read from a zip archive python

I want to create a comic archive reader in python as an exercise to teach myself more python but I've been having troubles trying to read different image files from a zip archive without extracting the files and then display them.
I found a website with an example (http://www.python-forum.org/pythonforum/viewtopic.php?f=4&t=3607) that could only display .gif images. The example uses PhotoImage (The Tkinter version not the PIL version) which can accept a 64bit encoded string instead of an actual file. From most of my research it looks like PIL is what I want to use to deal with images other than gif but I can't find a way to call PIL.ImageTk.PhotoImage in a similar way to the Tkinter.PhotoImage. to take a stream of data instead of an actual file.
Is there any way that I can hand the data received from zipfile.read() to PIL.ImageTk.PhotoImage? Is there another library I could use to handle the images? Tkinter is not a requirement for the program I'm writing so if there is a better widget framework that I should be using I don't mind changing.
EDIT:
So I figured a way to do this with PIL and tkinter.
z = zipfile.ZipFile("zipfile.zip", "r")
data = z.read(z.namelist()[0]) #Read in the first image data
dataEnc = StringIO(data) #Encode the raw data to be used by Image.open()
img = Image.open(dataEnc) #Open the image
pimg = ImageTk.PhotoImage(img) #Make tk compatible image
You can use PythonMagick to create an Image like so:
from PythonMagick import *
data = zipfile.read()
img = Image(Blob(data))
Then display it using wxPython as suggested in the PythonMagick readme under the "Display" section.

How does Django determine if an uploaded image is valid?

I'm trying to add images to my models in my Django app.
models.py
class ImageMain(models.Model):
"""This is the Main Image of the product"""
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
In development mode, every time I try to upload the image via Django admin, I keep getting:
Upload a valid image. The file you uploaded was either not an image or a corrupted image.
The jpg I'm trying to upload can be viewed with os X Preview so it would seem to be valid.
It seems the problem is Python Imaging Library doesn't recognize it as an image. Why would that be happening with a valid image?
PIL is installed, verified via the Django shell.
According to Django's source code. Those three lines are responsible for verifying images:
from PIL import Image
trial_image = Image.open(file)
trial_image.verify()
The image type could be unsupported by PIL. Check the list of supported formats here
Did you try uploading image format like gif or png? It might be that your PIL was not built with the jpeg lib properly. I had a similar issue with Django on Ubuntu. If you have ever seen the error message decoder jpeg not available, check this link. Relevant line from the link:
$ cd libImaging
$ ./configure --with-jpeg=/somelib/lib --with-zlib=/somelib/lib
I looked into the Django source, in django/forms/fields.py, in the ImageField class. Django actually does use PIL to determine when an image is valid.

Categories

Resources