PIL Python3 - How can I open a GIF file using Pillow? - python-3.x

In my current condition, I can open an Image normally using a really short code like this
from PIL import Image
x = Image.open("Example.png")
x.show()
But I tried to use GIF format instead of png, It shows the file but it didn't load the frame of the GIF. Is there any possible way to make load it?
In My Current Code
from PIL import Image
a = Image.open("x.gif").convert("RGBA") # IF I don't convert it to RGBA, It will give me an error.
a.show()

Refer to Reading Sequences in the documentation:
from PIL import Image
with Image.open("animation.gif") as im:
im.seek(1) # skip to the second frame
try:
while 1:
im.seek(im.tell() + 1)
# do something to im
except EOFError:
pass # end of sequence

Related

Is there a way to save an adjusted image from a named Window in opencv in Python?

Just a general question - I made a contrast slider, so I could open images and adjust their brightness and/or contrast to what best fits my needs. However, how can I save those settings resp. overwrite the image with those settings once I close the window?
Unless I am misunderstanding your question, I think you just need to make sure you are saving the adjusted image to a different file path. The code below might help you. You can insert the datetime into the file name if you want a new image to be saved each time.
import cv2
from datetime import datetime
def some_adjustment(img):
"""
your adjustment
"""
return img
path = "img.jpg"
img = cv2.imread(path)
adjusted_img = some_adjustment(img)
cv2.imshow('adjusted_img', adjusted_img)
cv2.waitKey(0)
now = datetime.now()
dt_string = now.strftime("%m.%d.%Y.%H.%M.%S")
cv2.imwrite(f"adjusted_{dt_string}.png", adjusted_img)
cv2.destroyAllWindows()

How to read an image from Google Drive using Python?

I want to read image from drive and convert to binary.How can I do that? I used this code but not get the actual image.
link = urllib.request.urlopen("https://drive.google.com/file/d/1CT12YIeF0xcc8cwhBpvR-Oq0AFOABwsw/view?usp=sharing").read()
image_base64 = base64.encodestring(link)
1. Download the image to your computer.
2. You can use cv2 to convert an image to binary like so:
import cv2
img = cv2.imread('imgs/mypic.jpg',2)
ret, bw_img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)

cv2.cvtColor(img,cv2.COLOR_BGR2RGB) not working

I am trying to create a screen recorder using mss and Opencv in python, the video I am capturing has a very different colours than original computer screen. I tried to find the solution online, Everyone saying it should be fixed using cvtColor() but I already have it in my code.
import cv2
from PIL import Image
import numpy as np
from mss import mss
import threading
from datetime import datetime
`
def thread_recording():
fourcc=cv2.VideoWriter_fourcc(*'mp4v')
#fourcc=cv2.VideoWriter_fourcc(*'XVID')
out=cv2.VideoWriter(vid_file,fourcc,50,(width,height))
mon = {"top": 0, "left": 0, "width":width, "height":height}
sct = mss()
thread1=threading.Thread(target=record,args=(mon,out,sct))
thread1.start()
def record(mon,out,sct):
global recording
recording=True
while recording:
frame= np.array(sct.grab(mon))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
out.release()
the vid_file variable contains a string of output file name with mp4 extension
Screenshot of my screen
Screenshot from recorded video
So, I looked around some more and found that apparently this is a bug in opencv for versions 3.x on wards.then I tried PIL for getting rgb image and removed cvtColor(),but it produced an empty video.I removed both cvtColor() as well as PIL Image as suggested by #ZdaR it again wrote empty video Hence I had to put it back and boom. even if cvtColor() seems like doing nothing, for some unknown reason it has to be there.when you use PIL Image along with cvtColor() it writes the video as expected
from PIL import Image
def record(mon,out,sct):
global recording
recording=True
while recording:
frame=sct.grab(mon)
frame = Image.frombytes('RGB', frame.size, frame.rgb)
frame = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2RGB)
out.write(np.array(frame))
out.release()
as I am very new to programming, I would really appreciate your help if I missed or overlooked something important
You can do
frameRGB = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
Frame is in BGR, and it will work the same as you are only changing R with B where frameRGB is in RGB now. This command will transfer R to B and works to transfer frames from RGB and BGR as well as BGR to RGB. BGR2RGB might be a bug, I have it as well but the command I mentioned works perfectly. That's what I do.
MSS store raw BGRA pixels. Does it work if you change to:
# Grab it
img = np.array(sct.grab(mon))
# Convert from BGRA to RGB
frame = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
you should run this command in cmd
pip install opencv-python

How do i close a figure shown using matplotlib in python ? And What is difference among image, figure and picture?

I am using ubuntu. I want to close a figure shown using matplotlib after few seconds without using keyboard or mouse. I am able to close an image shown using PIL after few seconds by getting its process id and then kill it.
And i am also little bit confused among terms figure, image and picture in matplotlib.
Thank you so much in advance.
Regarding part 1.
i have used plt.close(), plt.close("all") as well as 'psutil' library to fetch process ID and kill. But none of them worked. I got only solution of closing an image opened via 'PIL'.
link :-
How can I close an image shown to the user with the Python Imaging Library?
Regarding part 2.
Actually, at some pages, i found the terms 'figure','picture' and 'image' were used interchangeably; and at some pages they were not. I saw 'plt.imshow()' is used for image and picture and 'plt.show()' is used for figure. But, what is difference between figure, image and picture. And when to use these functions?
link :-
Why plt.imshow() doesn't display the image?
# for graphing
import matplotlib.pyplot as plt
import time
# for process
import psutil
# importing for image processing
from PIL import Image
#### closing an image which was opened via PIL
#### working perfectly
filename = "check.jpg"
img = Image.open(filename)
img.show()
time.sleep(5)
# for killing process such that image viewer
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
#### closing an image/figure which was opened via matplotlib
#### unable to close without keyboard or mouse
x = [[1,2,3,4],[11,22,33,44],[9,8,7,6]]
print (x)
plt.imshow(x)
plt.colorbar()
plt.title("a")
plt.xlabel('b')
plt.ylabel('c')
a = plt.show()
time.sleep(2)
## not working
plt.close()
## not working
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
## not working
plt.close("all")
i expect that my shown figure closes automatically after a few seconds,
instead of any manual intervention.

Raw Images from rawpy darker than their thumbnails

I'm wanting to convert '.NEF' to '.png' using the rawpy, imageio and opencv libraries in Python. I've tried a variety of flags in rawpy to produce the same image that I see when I just open the NEF, but all of the images that output are extremely dark. What am I doing wrong?
My current version of the code is:
import rawpy
import imageio
from os.path import *
import os
import cv2
def nef2png(inputNEFPath):
parent, filename = split(inputNEFPath)
name, _ = splitext(filename)
pngName = str(name+'.png')
tempFileName = str('temp%s.tiff' % (name))
with rawpy.imread(inputNEFPath) as raw:
rgb = raw.postprocess(gamma=(2.222, 4.5),
no_auto_bright=True,
output_bps=16)
imageio.imsave(join(parent, tempFileName), rgb)
image = cv2.imread(join(parent, tempFileName), cv2.IMREAD_UNCHANGED)
cv2.imwrite(join(parent, pngName), image)
os.remove(join(parent, tempFileName))
I'm hoping to get to get this result:
https://imgur.com/Q8qWfwN
But I keep getting dark outputs like this:
https://imgur.com/0jIuqpQ
For the actual file NEF, I uploaded them to my google drive if you want to mess with it: https://drive.google.com/drive/folders/1DVSPXk2Mbj8jpAU2EeZfK8d2HZM9taiH?usp=sharing
You're not doing anything wrong, it's just that the thumbnail was generated by Nikon's proprietary in-camera image processing pipeline. It's going to be hard to get the exact same visual output from an open source tool with an entirely different set of algorithms.
You can make the image brighter by setting no_auto_bright=False. If you're not happy with the default brightening, you can play with the auto_bright_thr parameter (see documentation).

Resources