HomeОбразованиеRelated VideosMore From: Corey Schafer

Python Tutorial: Image Manipulation with Pillow

1046 ratings | 99560 views
In this video we will learn how to modify and manipulate images using the Python Pillow Library. Pillow is a fork of the Python Imaging Library (PIL). It will allow us to do many different things to our images such as: changing their file extension, resizing, cropping, changing colors, blurring, and much more. Pillow is extremely useful when you have multiple images you wish to process at once. For example, you can use Pillow to automatically create different sized thumbnails of images you upload to your web server. Let's get started. If you enjoy these videos and would like to support my channel, I would greatly appreciate any assistance through my Patreon account: https://www.patreon.com/coreyms Or a one-time contribution through PayPal: https://goo.gl/649HFY If you would like to see additional ways in which you can support the channel, you can check out my support page: http://coreyms.com/support/ Equipment I use and books I recommend: https://www.amazon.com/shop/coreyschafer You can find me on: My website - http://coreyms.com/ Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Google Plus - https://plus.google.com/+CoreySchafer44/posts Instagram - https://www.instagram.com/coreymschafer/ #Python
Html code for embedding videos on your blog
Text Comments (82)
Matthew Stidham (17 days ago)
Super helpful, thank you!
Nia Bria (20 days ago)
how to make 2 image in display python with pillow at the same time. thankyou
Bon Bon (22 days ago)
OK, now after I learned how to make Instagram, how about generating images pixel by pixel? (e.g. some procedural images or fancy image filtering)
Vasu Deo.S (25 days ago)
Awesome Video. Just a little rectification. The "L" mode that you used for converting your image into black and white, is actually for converting an image into greyscale. A black and white image only consists of 2 colors (Black & White) and the image that you converted had several shades of grey(0-255). For Converting an image into black and white you have to use "1" mode which stands for 1 bit per pixel which truly resembles a Black & White image, use that in disabled dither mode to actually see the black and white image otherwise you will see you image with grainy noise. You can sort of see this just by looking at the image, a black and white image should just contain black and white not any other color.
Yates Snyder (27 days ago)
i had installed Pillow but my decoder zip isn't available ...........
ankit agrawal (2 months ago)
hey the result of my (print f ) is random. How can i get that in oder starting from 0 till what ever number i have ? thankyou!
동글 (2 months ago)
the best best best python tutorial ever. More of python tutorial would be appreciated!!
동글 (2 months ago)
love it!!
Jan Antonín Kolář (2 months ago)
Thank you!
chitra lalawat (3 months ago)
Hey! can you tell me how to get pixel value by mouse clicking on that part of image??
Tony T (3 months ago)
Excellent tutorial! Thank you!
Hassan Abbasi (3 months ago)
@bhawna I guess this code could do what you want if I understood right: import os from PIL import image image_name = input("Please Enter Image Name:") for f in os.listdir('.'): fn, fext = os.path.splitext(f): if image_name in 'fn': i = image.open(f) i.show()
The best python teacher...
rohit pattnaik (4 months ago)
Very Very helpful videos man .... Keep them coming :)
ARCENIO CORNEJO (4 months ago)
Simple and straight to the point. Thanks.
memes and AMV (4 months ago)
Can we use pillow for image authentication?
Farhanking7864 (4 months ago)
its incredible how python makes our lives so much easier lol
Ernest G. Wilson II (4 months ago)
Another great video, thank you for making this and sharing it with all of us! Following along this video and referencing another video that you made, would it be advisable to make a context method for doing image manipulation? One of your previous videos uses something you call a context method for opening and closing files, but in that video you mention a context method could be created for various other tasks, I am wondering if this image manipulation would be applicable?
K4LI_L1NUX _PR0 (4 months ago)
RIP to windows users. fuck you.
Q25Q25Q (5 months ago)
I line for line have the exact same code and it will crop the image, but only along one axis. Original was 1024x768. New image is 300x200
Richard Finney (5 months ago)
Thank you so much!!! Awesome tutorial and very much appreciated :)
Lavamar (5 months ago)
I think you make the best python tutorials on YouTube.
Supriyo Mukherjee (5 months ago)
It shows pilkit can not import images library
anil gupta (5 months ago)
thanks a lot , this is very helpful videos.
Aart Hakkens (6 months ago)
Does anyone know how I could add more canvas to an image?
Ujwal Bhargav Tadur (6 months ago)
Sir, Can you please make videos on Django Framework as well ?
satya prakash gaurav (7 months ago)
Hi Corey, Do you know how to take the partial screen shot of any image or any URL. How to crop?
kapil sharma (8 months ago)
Hey schafar, I love to watch your tutorials on python . And it seems the way you explain the things directly get into mind . I would request you to please make tutorials on django for website . Really appreciate your work
ahmed634899 (8 months ago)
I would like to thank you from the bottom of my heart for this tutorial
Kevis Rucyahana (9 months ago)
Really simple. easy to understand. Thanks a lot!
T REVATHI (10 months ago)
Heloin42 (10 months ago)
fantastic tutorial, thank you!
beautifull life (10 months ago)
Is it ok if I use this in Django..production mode
Hey me (10 months ago)
Sir, how can I crop images(say 25) at once
Lac-Phong Nguyen (10 months ago)
+Corey Schafer what code editor do you use
Corey Schafer (10 months ago)
Hey There. This is Sublime Text. I made a video on how I set up this Python development environment. You can find that video here: https://www.youtube.com/watch?v=xFciV6Ew5r4 Thanks!
syed Abdul rahim (10 months ago)
How do I concatenate two images horizontally??
bhawna (11 months ago)
hi, how can I display image during runtime from my folder as per requirement? for eg., if I write apple then it will show image of an apple stored in my folder.
santhosh patel (6 months ago)
me aslo same doubt
Sameena Shaikh (11 months ago)
Hi, Can you do a video on using piexif library for images to geotag gps data to the images through python programming. Would really appreciate that. Your videos are clear and easy to understand.
Doug Smith (1 year ago)
Good video. Very handsome puppy.
Abhiram Kumar (1 year ago)
How do you reverse the bits of an image?
David (1 year ago)
Nice video. Extra points for dogs. Subscribed and Bookmarked :)
cartoonjerk (1 year ago)
Thanks a lot for the detailed tutorial. I am wondering if you can do one on the Python 3 version as it is quite different than the one you showed here. Still regardless thanks a lot! It really helps as a start. Also I am using a windows platform, do I still need that os.listdir code? Thanks!
AnOrderedHole (1 year ago)
I had a hell of time installing pillow. It turns out I had 64 bit & 32 bit python installed which made it impossible to install it. I had to uninstall python and it worked.
lionpersia (1 year ago)
I looked up online but I couldn't find it. The method PIL.Image.getpixel(x, y) is 0-based or 1-based? I mean, do the coordinates start from 0 or do they start from 1? Thank you in advance.
Ziad Awwad (1 year ago)
Oleg Dyatlenko (1 year ago)
I guess it comes handy to make pics smaller. But rotation or color changing much better do with js on frontend part.
128Gigabytes (1 year ago)
Hey Corey is it possible to create new images using PIL instead of just editing?
Corey Schafer (1 year ago)
That may be true, but I would argue there are use cases for modifying images in this way outside the context of a website.
Leyton Jay (1 year ago)
I need to edit individual pixels in a bitmap and then save it off to a jpg. No one seems to know how to do it.
ORGANIC PIANO (1 year ago)
img = Image.new( 'RGB', (250,250), "black") # create a new black image pixels = *img.load() # create the pixel map* ... *pixels[i,j] = (i, j, 100) # set the colour accordingly* https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels
Satadhi Halder (1 year ago)
did  u find it  i need to do the same !
Hany Abdelbaki (1 year ago)
PS C:\test> python.exe imagemanipulationwithpillow.py Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\PIL\JpegImagePlugin.py", line 602, in _save rawmode = RAWMODE[im.mode] KeyError: 'P' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "imagemanipulationwithpillow.py", line 18, in <module> i.save('300/{}_300{}'.format(fn, fext)) #changing the path using /pathname File "C:\Program Files\Python36\lib\site-packages\PIL\Image.py", line 1893, in save save_handler(self, fp, filename) File "C:\Program Files\Python36\lib\site-packages\PIL\JpegImagePlugin.py", line 604, in _save raise IOError("cannot write mode %s as JPEG" % im.mode) OSError: cannot write mode P as JPEG PS C:\test>
jb (1 year ago)
Excellent tutorial, very clear. Thank you +
RagHelen (1 year ago)
It would have been better to use a distant location for the image directory, as it is the more realistic scenario and it can't be solved with splitext that easy.
Anwar Roba (1 year ago)
Clear and precise! thank you
MikeZ (1 year ago)
# this my code from PIL import Image image1=Image.open('we.gif') image1.show() # this is the error C:\Python\python.exe C:/PyProjects/learnpy/filesANDdir.py Traceback (most recent call last): File "C:/PyProjects/learnpy/filesANDdir.py", line 1, in <module> from PIL import Image File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\PIL\Image.py", line 67, in <module> from PIL import _imaging as core ImportError: cannot import name '_imaging' Process finished with exit code 1
Corey, I wish you could talk about byte datatype and its usage at low level stuff(like windows/unix files). I think, your intro stuf with this series will avoid me reading "dive into python" book
aykut sirma (1 year ago)
Where do I need to put my image into which file ( I use windows operation system ) ? I really cannot insert image to tkinter by using python 3.6.0 version, would you make a tutorial about it too please or at least would you guide me about this issue how we do it ? thank you very much. I cannot find a clear tutorial regarding this issue I experience so far, would you help me plz ? tyvm
Akif ARSLAN (1 year ago)
Thank you for nice videos. But i can't install and run this hombrew. Akifs-MacBook-Air:~ ars.akif$ Akifs-MacBook-Air:~ ars.akif$ $ pip install Pillow -bash: $: command not found Akifs-MacBook-Air:~ ars.akif$ $ easy_install Pillow -bash: $: command not found Akifs-MacBook-Air:~ ars.akif$ $ ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)" curl: (22) The requested URL returned error: 400 Bad Request -bash: $: command not found Akifs-MacBook-Air:~ ars.akif$ tryed many others from help sites. didnt work :(
Cooly (1 year ago)
Ewwwww, apple device...
Mussa Charles (1 year ago)
I did it by just copy and paste the command given on this link https://brew.sh and then to install pillow I made it by typing:- pip3 install pillow
Karan Sharma (1 year ago)
Sir, how to change aspect ratio as well. thumbnail(size) only change size and that to a limit that don't change the aspect ratio of the image so, how can we ensure that all images have same aspect ratios and a uniform size(like 300 x 300 and not something like 300 x 250 )
MasayoMusic (2 years ago)
Thanks. very interesting video.
Hi Excellent Tutorial. Can you please teach us how we can compare images from two folders. eg file1 will have image1,image2,image3,image4,image5 and file 2 will have image1,image2,image3,image4,image5. i wanted to compare from file one images with file2 image one by one and if they are different i want to print out the name of the file image.
Pure Suspense (2 years ago)
I am not able to display the image even after i pasted the image in the same folder where the python and python interpreter is, help me ... The error is 'File not Found'
João Olavo (1 year ago)
You have to have the files in the directory where you have your program code, not the python interpreter. Pay attention to the name of the files and the extensions too.
Michael Tran (2 years ago)
Thanks much! Great tutorial! I created similar and it works, I got the picture to resize . However, one problem I have is that when I converted this .py into an app using command "sudo python setup.py py2app", and then ran the app under /dist I got an error message "resize_pix_module Error" pops up of which I could not figure out what's wrong. The Log didn't really help pinpoint. Would you kindly help with some tips? Would very much appreciate. I am helping to build a website for a non-profit organization and and one of the mission of the site is for charity. I am handling IT stuff, am trying to resize many photos to upload, taking advantage of this tutorial to save time by using the script. ----------------resize_pix_module.py---------------------------------------- from PIL import Image import os size_300 = (300, 300) for f in os.listdir('.'): if f.endswith('.jpg'): i = Image.open(f) fn, fext = os.path.splitext(f) i.thumbnail(size_300) i.save('300/{}_300{}'.format(fn, fext)) ---------------------------------------------------------------- ---------------------setup.py------------------------------------------- """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['resize_pix_module.py'] DATA_FILES = [] OPTIONS = {'argv_emulation': True} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'] )
HaguDeGozaru (2 years ago)
Thanks for this concise demonstration.
Austin Chen (2 years ago)
hey, thank you for the tutorial. I encountered a problem when using os.listdir() os.listdir('.') worked fine but if I change the path to another one like os.listdir('/home/agfa/Downloads') it will show IOError: [Errno 2] No such file or directory: 'hand1.jpg' I don't know why QAQ
eddy effervescence (2 years ago)
How are you running your command? Each time you do it you click off-screen and bang, the program works! I have to terminal each and every time. It seems like you're using Sublime Text, or something formateed very similar. Very interseted in this answer and in watching more of your videos because...this one was the best programming video I've ever seen yet.
Sawtooth (1 year ago)
I'm using pycharm. It similarly uses Cmd+r to execute code. If you have to use terminal every time, you can maybe try out pycharm. There are two free versions: community (PC), and Education (PE).
Corey Schafer (2 years ago)
Hey there. I'm not clicking off screen, I'm just pressing Cmd+b. That is how you run code within Sublime Text. There are several other ways we could execute it via the terminal, but this is how I usually do it in my videos. Thanks for the question.
Daniel Weikert (2 years ago)
Great video. Is there a way to tell python to go to a webserver, login and enter the folder to change the files there or does this only work locally? Thanks
Corey Schafer (2 years ago)
I'm sure there are ways you can do that. Is this a webserver you have access to? If so, it may be worthwhile to install python on that server and maybe run a cron task to do what you want on a regular basis. I'm not sure of your usecase exactly, but we do things like that at my work a lot. Hope that helps. Thanks.
Hemalatha Bhagavan (2 years ago)
could you please post to crop multiple images(for eg:300 images) in a folder using Pillow(PIL). It would be highly helpful
Credible Mulk (2 years ago)
Please do a vid that uses image.blend to composite 2 images using an alpha. Thanks
DANJUMA9 (2 years ago)
Awesome, was looking for this. Thanks.
walass907 (2 years ago)
very good video ! thx
FLORIN RACOVEANU (3 years ago)
Hi! What code shall I use, in Python when I have to check automatically like 400 high resolution photos(RGB,thermal,and daylight)? The program shall detect sub-milimmiter anomalies(like small cracks) inside of each photo,if any,if not should scan the next one,etc.Exemple of inspection:wind turbines,flare stacks,etc. Thanks in advance, Costel
Wesley Satelis (2 years ago)
+FLORIN RACOVEANU I guess you&#39;re gonna have to figure that out, isn&#39;t that what programming is supposed to be? https://pypi.python.org/pypi/PIL this might be a good way to start. Happy coding!

Would you like to comment?

Join YouTube for a free account, or sign in if you are already a member.