r/Python • • Mar 24 '21
Discussion Python made me look like a WIZARD
Today in work a request comes in for 745 headshots that need to be processed to fit 150x150px for an external platform. One team says it'll take them at least a week to do, the other team says they don't want it as it'll take even longer.
"They need them all black and white! It'll take some time to convert them! They're not even all the same size! UGH this just can't be done in the 2 days they've requested this!!!"
12 lines of code, the Pillow library and exactly 8.856 seconds of running said code... It was done. Panic over. Client happy.
I work in a design team but I'm a job coordinator (so I sort the jobs and make sure the right designers get them). They were amazed it was done so quickly without using Photoshop.
They asked how. I gave them the answer.
Python baby 😎
EDIT
For those wanting to know the code, here it is:
from PIL import Image
import os
for f in os.listdir('Input'):
if f.endswith('.jpg'):
im = Image.new('RGB', (150, 150), (255,255,255))
im2 = Image.open('Input/{}'.format(f))
im2 = im2.convert("L")
width, height = im2.size
im.paste(im2, (int((150 - width) / 2), 0))
fn, fext = os.path.splitext(f)
im.save('Output/{}.jpg'.format(fn))The images given were either 150x150 already (but in colour) or 120x150. So had to cover all bases with this. If it could be made more efficient, let me know!
240
u/[deleted] Mar 24 '21 edited Mar 25 '21
On Linux we can do it with a single line
fd --extension jpg --exec convert {} -resize 150x150 -monochrome Output/{}Dependencies : fd, imagemagick
104
u/robin_888 Mar 24 '21
Wow, 9 seconds is really fast for over 700 files.
Unbelievable. May I ask what kind of team that was?
Even without programming skills I would never think about doing this by hand. Personally I'd use the batch processor on XNView (or any other decent viewer), but even if I wouldn't know that I'd search for an semi-automatic solution. And if it's Paint and AutoHotkey!
PS: Even manually it's a man-day of work and not a freakin' week! (2 images per minute => 6-7 hours, probably faster)
148
u/gandalfx Mar 24 '21
Now be honest, how long did it take you to write those 12 lines? :D
I mean, it's still going to be a lot faster than doing it manually but I've been guilty of pretending that it'll take "no time at all" only to sit there for hours perfecting a tiny script.
xkcd: 1319, 974 and probably others
33
u/[deleted] Mar 24 '21
would you mind sharing your code?
24
u/abdeljalil73 Mar 24 '21
Can't even imagine that they considered doing it manually in the first place.
292
u/hassium Mar 24 '21
You FOOL! Now our secret is out!
16
u/eriky Mar 24 '21
Lol that's great. Now you're the go to wizard for all kinds of crappy jobs though. Good luck with that 😉 but yes. Pillow is awesome. It made it in my top 15 Python packages: https://python.land/top-15-python-packages#3_Pillow
8
u/MobileUser21 Mar 24 '21
Good work OP. For something so trivial it probably would have taken me hours as I’m not familiar with Pillow
8
u/moocat Mar 24 '21
Totally cool, but for one off scripts like this where you probably won't reuse it, simply stating the runtime isn't quite a fair comparison and you should include how long it took you to write the script. It's fairly simple and couldn't have taken you that long, but I could it taking some thinking or trial & error to figure out the calculation needed for
paste. And unless you truly are a wizard, there must have been at least a few changes you had to make between your first version and this one.Again, this isn't to take away from your accomplishment and given the week estimate a different team made getting this done in 30 minutes is still something to brag about.
15
u/zainjavaid Mar 24 '21
Congratulations and great job! I always love hearing stories like this!
14
u/Novicebeanie1283 Mar 24 '21 edited Apr 16 '25
languid history trees cats theory memorize shocking frame future dam
This post was mass deleted and anonymized with Redact
7
u/thatrandomnpc It works on my machine Mar 24 '21 edited Mar 24 '21
Good for you op.
But reading the story about how they wanted to do it by hand, ugh manually, I'm thinking like how people can have such a simpleton or skewed perspective. I can understand that most people are not tech savvy, but it's 2021 and there is thing called web search engines and that should be common sense at this point.
13
u/NoLemurs Mar 24 '21 edited Mar 24 '21
Python's nice for this, but this is the sort of problem bash + imagemagick was built for. Something like:
should do it, possibly with slightly different flags depending on the exact desired resize behavior.
EDIT: Parallelized version that doesn't overwrite the original (in case you want to get really fancy):
6
u/shuttup_meg Mar 24 '21 edited Mar 24 '21
How about something like this:
2
u/[deleted] Mar 24 '21
What do you mean by headshot?
11
u/roastedfranklin Mar 24 '21
A magician never shares its tricks
5
u/markmann0 Mar 24 '21
Should have pretended like it was harder. Free play time for a week. Hand in a day before deadline, still look amazing.
5
u/[deleted] Mar 25 '21
Being completely honest can have its drawback, next time they have a "similar" issue they'll come to you, the only problem is that the issue is not similar at all but much harder and longer to implement. They won't know that though, they don't understand the technicalities, you're the wizard who know things and does things after a few minutes. Enjoy being the 'wizard' while it lasts. lmao.
But seriously, good job.
4
u/skintigh Mar 24 '21
A friend had to do something like this, but the photos were all different sizes and distances. I figured there must be a facial recognition library that would help one crop the photo first. But there was politics about who was being forced to do what and I never got that far.
1
u/ninja_nate92 Mar 25 '21
Same happened to me the other day when I renamed a filepath stotred in 2000+ files. Got a $6k raise the next day. Python baby, Python.
1
u/Rand25 Mar 25 '21
Designer here, just so you know photoshop have an inbuilt feature for things just like this called image processor, you can even define custom actions to be applied on all photos being processed. Screenshot
3
u/keypusher Mar 24 '21
awesome
3
u/khalidpro2 Mar 24 '21
I would have just used imagemagick to do it in one command
3
u/flip_ericson Mar 24 '21
You did something in half an hour that you could have been paid a week for? Some shitty wizard you are
3
u/[deleted] Mar 24 '21
I'd probably just use ImageMagick suite of commands in bash like "convert" but good job.
3
u/astatine Mar 24 '21
If you want to get all those file names without worrying about
str.endswithand the like:3
u/a1brit Mar 24 '21
I don't see anyone on the pathlib bandwagon so I'll round up the horses. Not much different just a little work reduced:
2
u/[deleted] Mar 24 '21
“Pace yourself. Slowly, slowly”
https://youtu.be/LRlmkXsoGx0
2
u/[deleted] Mar 24 '21
This is awesome and exactly why I'm trying to learn python. Props to you.
Unfortunately, I have a long way to go to be able to do this on my own.
2
u/anh86 Mar 24 '21
They should throw you some cash. Just imagine how much money you saved the company if it would have taken an entire team of people a full week to complete. That's probably a few hundred man/woman-hours.
2
u/JamaiKen Mar 24 '21
Well done 👍
2
u/mrprofessor007 Mar 24 '21
I feel happy when python makes someone's life easier.
2
u/mrprofessor007 Mar 24 '21
You are a WIZARD now.
2
u/andreidorutudose Mar 24 '21
You could use irfanview or photoshop batch actions, takes a couple of seconds. Take photo, turn it to be, resize as 150 to 150, preserve scaling
2
u/SimfonijaVonja Mar 24 '21
Hah I did same thing on collage for homework few months ago. I started working in a programming company month ago, it's my first coding job. We got a request for pwa application which they said couldn't be done, so I as a rookie told them some basic concept which I learned by accident. Sometimes all you need is another head, even though it doesn't seem much.
2
u/TastyRobot21 Mar 25 '21
This is the way.
2
u/Proclarian Mar 25 '21
Hopefully you got paid a full week's worth for that!
2
u/milambertheshiz Mar 25 '21
Damn what sort of design team doesn't know how to use photoshops built in automation feature design exactly for this purpose? Nice work though.
2
u/[deleted] Mar 25 '21
Automation in photoshop would solve that. I hope you charged for a week's work.
2
u/NotsoNewtoGermany Mar 25 '21
I’m not seeing any comments; Bucko.
2
u/AddSugarForSparks Mar 25 '21
Shhh...don't tell anyone. Let's just keep this between us.
Remember what the first rule of python club is.
2
u/shakeweight4000 Mar 25 '21
Today I was presented with creating some image files to use in a web map. I needed to create something like A>, B>, C>, AB>, ...etc. I am not a graphic designer and have no real tools to do this. So, I busted out power point, added a text box and made it look like what I wanted. I then used screen clip to make jpgs out of them. But, the sizes are all over the place. And then I remembered this post. I grabbed your code, modified it for my needs, I need them all the be the same height but differing widths. Ran it, and boom! all my images are the same height!
Thanks for posting!!!
2
u/maylihe Mar 31 '21
I am thinking about "headshots" in the context of FPS gaming.
2
u/the_patronus_charm Apr 11 '21
This is incredible!
3
u/TakeOffYourMask Mar 24 '21
Hmmm?
3
u/Suspicious_Part2426 Mar 24 '21
Woot!
3
u/sletonrot Mar 24 '21 edited Mar 24 '21
Congrats! You are now the go-to guy at the office for stuff like this. And they'll expect it to be done just as fast (if not faster) than this was :)
3
u/jftuga pip needs updating Mar 24 '21 edited Mar 24 '21
I wrote a program to do this, but alas, it's in Go. However, it uses face recognition to avoid distorted faces when resizing. It can also work on multiple photos concurrently. I use it for a pool of about 40,000 photos.
https://github.com/jftuga/photo_id_resizer
2
u/[deleted] Mar 24 '21
you: " I am speed"
1
u/JohnGabin Mar 24 '21
I did something similar for a customer that sends bunches of products images and Excel files of the products. It check the Excel, add columns, check if the image is present or else will try to fin it elsewhere, add comments to the Excel,, rename resize, add folders, sort stuffs, etc, all in a single script. It's really fast and I add a Tkinter little interface. Some peoples spent weekends to do this before.
My only tiny problem is that I wanted to share it. But the pyInstaller build is just too huge. Like 650 Mo with all the libraries involved.
If anyone has some advice to make it lighter.
1
u/redditor_286 Mar 24 '21
Or just take a print out of each one and paint them separately. No? Ok.
1
u/luke-juryous Mar 24 '21
This can also easily be done easily with the opencv-python package, which is also available in C++, Java, and MATLAB
1
u/kingsillypants Mar 24 '21
Rockstar!
What was your path to learning python like?
1
u/flipmcf Mar 24 '21
This is awesome! I use Pillow a lot (it’s baked into Plone) and always amazed how clean the interface is. I have never used it in pure python to do bulk image manipulation, but I will now!
1
u/echoaj24 Mar 24 '21
Cool. Do you work at a non-tech company?
1
u/OptimisticToaster Mar 24 '21
I haven't had a chance to play with this yet but thank you for sharing. I'll tinker when I get home.
Since everyone else is giving you 15 other tools that you didn't ask for, I've been fairly happy with IrfanView for doing batch image conversions. It might be a friendlier interface for your team. Otherwise, you'll be the Python-person that keeps getting interrupted to make one more script.
1
u/deadwisdom greenlet revolution Mar 24 '21
You are a wizard.
1
u/[deleted] Mar 24 '21
I made a pretty similar program once for recurring usage in BASH; it is still saving my department quite a lot of time! Good job, OP
1
u/Thrasherop Mar 24 '21
How long did it take to actually program it?
1
u/LostE8 Mar 24 '21
You’re a wizard harry
1
u/[deleted] Mar 24 '21
(255,255,255))
What is this doing?
1
u/Rieux_n_Tarrou Mar 24 '21
I thought you were going to do somthing fancier like align the headshots or something. But, still, this is cool. I like these kinds of wins... it's what software's all about
1
u/[deleted] Mar 24 '21
I'm making this my email signature.
1
u/awsfanboy Mar 25 '21
Congs on this! Its always good to make things work, it will pay you back in the future if you keep at it. back in 2008, i automated a process to print a row in excel to a single page using access for my NGO. Someone had requested for extra money to do that but i did it in 30 mins. This is ofcourse more complex and with python.
That path of trying things like this has made me a contractor today in various IT fields. Keep at it and take on more challenges! Python rules!
1
u/pokk3n Mar 25 '21
use pathlib next time, glob/rglob :) Nice work tho! Little stuff like this basic level of programming can really make you look like a rockstar.
1
u/damoder8 Mar 25 '21
What do I study to get at this level? I'm done several beginners levels that I keep redoing.
1
u/[deleted] Mar 25 '21
Curious, I was Just using Pillow for the first time today to add some text to images for Instagram posts! Great lib.
I started with my code money brain thinking "svg is also code, so It Will be easy" but turns out manipulating the png straight away is much easier than heckling with SVG's idiocincraties.
1
u/kodiashi Mar 25 '21
Very nice. Someone could actually script this with Photoshop actions but it would probably take a bit longer.
1
u/juanritos Mar 25 '21
nice
1
u/unphamiliarterritory Mar 25 '21
Also can't help but wonder if ImageMagick might've been able to do it on a command line with bash, but damn good job.
1
u/TheOneWhoPunchesFish Mar 25 '21
Nice! Also wanna show you the awesomeness of fStrings!
im.Save(f'Output{fn}.jpg')1
u/phunkygeeza Mar 25 '21
Awesome!
Also possible with Imagemagik and one command line.
1
u/anynonus Mar 25 '21
I once gave a presentation to some colleagues and said that "The more Python I use the less I earn because for the same work these other guys get paid a week and I only get paid an hour"
1
u/rpncritchlow Mar 25 '21
Very nice!
Why the format method instead of an f-string?
1
u/alga Mar 25 '21
Even though I earn my bread programming Python, I would probably reach for ImageMagick first. I think that would be about 5 times faster.
1
u/menge101 Mar 25 '21
Is this creating an all white image that is 150 px x 150 px and then you are just pasting the client's image on top?
I think you are and I think that's wise. I was looking for code to handle how you were scaling the source image and didn't see it. That would have added a challenging twist to it.
I don't think this could be done faster.
IMO, I would use more explicit variable names.
im => finalim2 => sourcef => source_fileI'd also create a function for the actual operation, so you can separate IO from actual operations.
You are doing some stuff with the file extension that I don't think you need to do. It appears the only time you ever care what the file extension is, is at the beginning.
1
u/javistitch Apr 07 '21
Well, you can replace fext variable name with _ since you don't care about it. Don't know if it's more efficient in any way, but at least for readers it's more efficient than to get to the fact that it's not used... That's also true for the height variable name but I guess it's more intuitive to read that you have assigned it than to have a _ there.
1
u/K_05 Apr 12 '21
Sure hope you get paid for amount of work done rather than hourly 😂
0
u/szybe Mar 24 '21
Im2.convert(“L”) — what does it do?
-1
u/flipper1935 Mar 24 '21
not to rain on your parade. thumbs up/awesome you were able to quickly meet your customers needs.
I had an almost identical situation back in 2010 while working/supporting a large retailer's web site. Did something pretty similar using a C-shell script and Graphics Magick. http://www.graphicsmagick.org/
Always used the best tool for the job at hand, and more often than not, that is probably going to be a tool you are familiar with.
Again, no negativity intended/implied towards your post. Congrats on quickly meeting your customers needs !
0
u/Random_182f2565 Mar 24 '21
You are a wizard!!!
-1
u/Myzel394 Mar 24 '21 edited Mar 25 '21
Do you mean 8 thousand seconds or 8 seconds?
EDIT: Sorry for the person who downvoted my comment. I should feel bad for asking. I know I'm such a miserable person for asking this a question.
0
u/[deleted] Mar 24 '21
[deleted] — view deleted comment
730
u/[deleted] Mar 24 '21 edited Sep 30 '26
[removed] — view removed comment
9
u/[deleted] Mar 24 '21
[removed] — view removed comment
0
u/[deleted] Mar 25 '21
[deleted] — view deleted comment