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

Python Tutorial: Image Manipulation with Pillow

1328 ratings | 119304 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. ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python
Html code for embedding videos on your blog
Text Comments (96)
D F (28 days ago)
I like it. Going to have to learn more about the OS feature and how to loop through files and such without destroying my own directories lol but this looks like exactly what I will use when I have a better understanding of how that part works. Thank you
D F (28 days ago)
+Corey Schafer Awesome Thanks a lot!
Corey Schafer (28 days ago)
I have a video on the OS module as well if you'd like to learn more about that in-depth. You can search for it on my channel
ryan derksen (29 days ago)
I am very appreciative that you are doing a tutorial on this but I am pretty sure you can do this without using other libraries. I could be wrong .
Lightning in My Hands (30 days ago)
You will be a legend in Python history.
Arjun Vc (1 month ago)
can you please explain how to read texts from images using python ? TIA
Cocoox (1 month ago)
You might wanna check out pytesseract. It's an optical character recognition tool that can extract text from images.
Gerhard A. E. Uhlhorn (1 month ago)
At the end: It’s not need to close and reopen the image. Preview is able to update an opened image. ;-)
Vasiliy (1 month ago)
4 years later and it's still relevant. Thanks alot!
Dennis (1 month ago)
I used pip install and it's worked without any problem lol
G PX (2 months ago)
Awesome tutorial!!! But I have a question, how did you find all that libraries, I mean, there are tons of them, how did you know which library is best for, say, image manipulation...or voice, or video.....Can you make a video about what kind of libraries that you use most often as a developer??? plz...
Lightning in My Hands (30 days ago)
try https://pypi.org
Vinod Kinoni (2 months ago)
Fabio Classo (2 months ago)
Amazing video
Slim Yelow (2 months ago)
great intro Thanks !
Matthew Stidham (3 months ago)
Super helpful, thank you!
Nia Bria (3 months ago)
how to make 2 image in display python with pillow at the same time. thankyou
Bon Bon (3 months 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 (3 months 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 (3 months ago)
i had installed Pillow but my decoder zip isn't available ...........
ankit agrawal (5 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!
광큐 (5 months ago)
the best best best python tutorial ever. More of python tutorial would be appreciated!!
광큐 (5 months ago)
love it!!
Jan Antonín Kolář (5 months ago)
Thank you!
chitra lalawat (6 months ago)
Hey! can you tell me how to get pixel value by mouse clicking on that part of image??
Tony T (6 months ago)
Excellent tutorial! Thank you!
Hassan Abbasi (6 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 (7 months ago)
Very Very helpful videos man .... Keep them coming :)
ARCENIO CORNEJO (7 months ago)
Simple and straight to the point. Thanks.
memes and AMV (7 months ago)
Can we use pillow for image authentication?
Farhanking7864 (7 months ago)
its incredible how python makes our lives so much easier lol
Ernest G. Wilson II (7 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 (7 months ago)
RIP to windows users. fuck you.
Q25Q25Q (8 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 (8 months ago)
Thank you so much!!! Awesome tutorial and very much appreciated :)
Lavamar (8 months ago)
I think you make the best python tutorials on YouTube.
Supriyo Mukherjee (8 months ago)
It shows pilkit can not import images library
anil gupta (8 months ago)
thanks a lot , this is very helpful videos.
Aart Hakkens (9 months ago)
Does anyone know how I could add more canvas to an image?
Ujwal Bhargav Tadur (9 months ago)
Sir, Can you please make videos on Django Framework as well ?
satya prakash gaurav (10 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 (11 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 (11 months ago)
I would like to thank you from the bottom of my heart for this tutorial
Kevis Rucyahana (1 year ago)
Really simple. easy to understand. Thanks a lot!
T REVATHI (1 year ago)
Heloin42 (1 year ago)
fantastic tutorial, thank you!
beautifull life (1 year ago)
Is it ok if I use this in Django..production mode
Hey me (1 year ago)
Sir, how can I crop images(say 25) at once
syed Abdul rahim (1 year ago)
How do I concatenate two images horizontally??
bhawna (1 year 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 (9 months ago)
me aslo same doubt
Sameena Shaikh (1 year 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 (2 years 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 (2 years 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 (2 years ago)
Ewwwww, apple device...
Mussa Charles (2 years 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 (2 years 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 (2 years 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
Gerald Eichentel (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 (2 years 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 (3 years ago)
Awesome, was looking for this. Thanks.
walass907 (3 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 (3 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.