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!

2.2k Upvotes

278 comments sorted by

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

38

u/[deleted] Mar 24 '21

We're all windows unfortunately!

51

u/jonasbxl Mar 24 '21

I am not saying it would have been easier or faster, but just in case you don't know about it: check out WSL https://docs.microsoft.com/en-us/windows/wsl/install-win10

15

u/ninj0rc Mar 24 '21

Just wanna say thanks for the link. I was unaware that this thing existed.

10

u/Rieux_n_Tarrou Mar 24 '21

After WSL2 came out, I've decided finally that my next laptop will be Windows (even though I really enjoy my macbook pro right now). Windows is better than Mac from the perspective of apps. And Linux is better than Mac from the perspective of software dev. So WSL is the best of both worlds IMO

0

u/[deleted] Mar 25 '21

[deleted]

→ More replies (1)

1

u/jonasbxl Mar 25 '21

It's really been a great addition to Windows. I've moved a lot of my dev tools to WSL, including Python actually - I never liked Anaconda too much and I find it easier to just manage my environments with virtualenv and virtualenvwrapper. You can still use VS Code from Windows; a shortcut to quickly open a directory from WSL is code . . That way VS Code uses Python (and virtual envs) installed on WSL.

11

u/riffito Mar 24 '21

IrfanView to the rescue! (and you do it all from the GUI with its batch-converter)

9

u/[deleted] Mar 24 '21

I guess you can install those programs on windows too using scoop or choco

0

u/[deleted] Mar 24 '21

[deleted]

4

u/khalidpro2 Mar 24 '21

installing choco is just one command that you need to paste and run in powershell

5

u/diamondketo Mar 24 '21

That's not the point. The point is people need to stop subjugating others to their own method when the OP is making a one off script.

One off scripts are just that, one off. It doesn't matter what method you do. If it gets the job done correctly in a reasonable time, do that. OP has the best judgement on which route OP should take given the knowledge and resource OP has at the time.

4

u/khalidpro2 Mar 24 '21

I totally agree with that, I just wanted to clarify that choco installation isn't that difficult

→ More replies (3)

7

u/[deleted] Mar 24 '21

The same can be said about writing python scripts, you need to which library, which functions and what parameters.

The idea behind my comments is todo with Unix philosophy.

Also the command line ans is 5x faster than python version

1

u/[deleted] Mar 25 '21

Hello windows, I am dad.

→ More replies (1)

31

u/EverythingIsFlotsam Mar 24 '21

*-resize

I assume

6

u/[deleted] Mar 25 '21

After using Linux and all these CLI tools for a while, I almost see no use for Python in these small tasks. Everything here can be done with a simple bash/zsh script in fewer lines than a Python script and no importing.

4

u/[deleted] Mar 25 '21

Yes that was my point. These are very small and easily automated tasks which we can do using CLIs

2

u/harolddawizard Mar 25 '21

I guess the use lies more in windows PC's.

3

u/davincible Mar 24 '21

`man fd` >> "Floppy drives are block devices ..." -- I don't think we're looking at the same command xd. Assuming you mean find

5

u/[deleted] Mar 24 '21

I don't think that is find, because as far as I'm aware it doesn't have an --extension test, and in any case the flags would be with one hyphen-minus sign not two, so something like find -name '*.jpg' -exec convert '{}' etc etc etc ';'.

1

u/[deleted] Mar 25 '21

fd does have --extension option.

I did a similar thing to op that I needed all the images to be in certain size(size on the disk) and in certain resolution for my image processing process.

Your solution is better because find comes pre installed on Linux distros.

I used fd because that's just a reflection action for me, I don't use find anymore

1

u/Offi12 Mar 26 '21

imagemagic also works on windows! can recommend it

104

u/robin_888 Mar 24 '21

Wow, 9 seconds is really fast for over 700 files.

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.

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)

46

u/[deleted] Mar 24 '21

It's a team that handle multiple design requests a day. So getting even a day to do this with no other work is impossible. They are constantly designing things. It's an in house design team for a law firm.

36

u/[deleted] Mar 24 '21

Shit, I work for a law firm too, it feels like a lot of them are complete technological backwaters. Peeps struggle to convert pdfs. I'm a tech wizard because I know how to paginate in Adobe.

11

u/[deleted] Mar 24 '21

Happens a lot, my old IT (before I switched teams) was helping us deploy dual monitors. 300 monitors were deployed and he plugged in a HDMI cable and a display cable from the docking station into 1 monitor. No word of a lie. I had to go round 150 desks and rectify the mistake. Another IT boss asked me how to attach a video from their iPhone to email. Baffled me how they were paid the big bucks!

10

u/[deleted] Mar 24 '21

Joke is that there are some places using neural networks to analyse legal document, and they're gonna run the dinosaurs out of business in the not too distant future.

Some judges are pretty bad too - I know of people that had to go into Court because the judge didn't know/was unwilling to learn how to do a remote hearing. In quarantine... during a pandemic... There was a clerk whose whole job was the get the judge a glass of water and bring lunch from the shop.

Thanks, stranger, I needed a good vent.

4

u/[deleted] Mar 24 '21

I wonder when we will see the first legal case defended by an AI

→ More replies (1)

21

u/kingsillypants Mar 24 '21

What is paginate in Adobe?

39

u/[deleted] Mar 24 '21

Bro, please you're triggering my PTSD. Adding page numbers to PDF documents in Acrobat.

10

u/proof_required Mar 24 '21

I do coding etc but never knew about this. You are a real tech wizard.

34

u/iroll20s Mar 24 '21

Well you have to account for time spent on hot memes and Starbucks runs.

1

u/dogs_like_me Mar 25 '21

The kind that would have done this one picture at a time in MS Paint? Oh wait no, this sounds more like a powerpoint-all-the-things kinda shop.

1

u/xaelix Mar 25 '21

They obviously don’t know how to run batch actions in Photoshop. I like how you did it the fun way.

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

72

u/[deleted] Mar 24 '21

It took 20 mins to work it all out in terms of what I needed to do and how to execute it - I had never used the PIL / Pillow library before! But worked it all out thanks to the documentation :)

86

u/SnowdenIsALegend Mar 24 '21

She said be honest. Come on man, credit StackOverflow, everyone knows no one reads documentation.

9

u/evkan Mar 24 '21

true. I read git commits.

0

u/[deleted] Mar 24 '21

[deleted]

6

u/flipmcf Mar 24 '21

Almost as good as the DateTime docs.

46

u/Dustin- Mar 24 '21

The real trick is learning how to make code that you're happy to throw away after you're done with it. Whip something up to do a quick job, do the job, get rid of the code. Doesn't matter how sloppy or efficient it is as long as it works.

25

u/djamp42 Mar 24 '21

I save everything..1 because if want to do the same task in the future I can go back and look what I did. 2) To see how far I've advanced and what I would of done differently.

12

u/[deleted] Mar 24 '21

What I've discovered as I've progressed is that for your case 1, it's actually slower for me to look at old code to see what I did. Usually the new use case is sufficiently different that it takes me longer to understand the old code and find the places it would need modification than it would take me to just write new code for the new use case.

Remember that looking at old code also involves those "hidden costs" of finding it, deciding where to write the new code (modify the old code in place or copy it into a new file/repo?), etc.

So now I take a sort of scorched earth policy in that I'll delete things not in use even if they seem useful and might come up again. If it's something really worth keeping, for some sort of historical reason or something, I'll make a branch called "terminal/some_old_implementation" and push it to the server just before making the commit to delete the code.

6

u/pycepticus from pprint import pprint as print Mar 24 '21

My cure for this approach was learning how to comment my code. It's an extra few hours depending on how large the project I wrote was, but being able to go back years later and not have to "human compile" my code has saved me rewriting large parts of similar projects in the future.

2

u/clestrada12 Mar 24 '21

Same. I love looking at old code I’ve done. I still have the first programs.

1

u/Numnumchips Mar 25 '21

This! I work where we mainly write safety critical cpp. So python is mostly used for quick tasks. In the beginning I often spend a lot of time perfecting these scripts just to later realize I only used them once.

0

u/[deleted] Mar 24 '21

How long does it take to Google the question is how long he has to code lol

2

u/gandalfx Mar 25 '21

You sound like someone who has never gotten stuck on something that turns out to be less trivial than it should. I.e. someone who has never written code.

→ More replies (8)

33

u/[deleted] Mar 24 '21

would you mind sharing your code?

11

u/[deleted] Mar 24 '21

shared!

23

u/[deleted] Mar 24 '21

You might enjoy pathlib over os and f-strings over format. pathlib.Path.rglob("*.jpg")!

I also don't know what Image.open does but sounds like a case for a context manager.

4

u/NAG3LT Mar 24 '21

You can do

with Image.open(filename) as im:
    ...

and close image automatically when you're done with it

0

u/[deleted] Mar 24 '21

[deleted]

4

u/xZeroKnightx Mar 24 '21 edited Mar 24 '21

Image.open itself is not a context manager, but it returns an Image (the class, i.e. Image.Image to be specific) object, which is a context manager as it defines the context manager interface: __enter__ and __exit__. As such, you can use Image.open in a with statement:

with Image.open('foo.png') as img:
    ...

Additionally, since Image.open is actually a module-level function in the Image module (can be a bit confusing), I'd argue that it's more of a factory1 than a constructor; though to be excessively pedantic, the __new__ method is Python's constructor as it is the method that actually creates an object instance.

[EDIT] Added a footnote


  1. For what it's worth, the Image.Image docstring refers to Image.open as factory.

1

u/diamondketo Mar 24 '21 edited Mar 24 '21

Good point, thank you for correcting me. I've made an edit.

You are correct in semantics but I'd argue pragmatics is more useful. At the end of the day constructor and factory returns to you the same object.

1

u/BluishInventor Mar 24 '21

What's a constructor? and what's it doing in this specific case?

I know I can google it, but I'd rather hear your answer.

3

u/diamondketo Mar 24 '21 edited Mar 24 '21

A constructor instantiates a class becoming an instance object. Sorry for the fkton of jargon our predecessors coined up. For example, the default constructor in Python is the __init__ .

In this case it is just ingesting image file and what you get back is a Pillow Image object. With this object you can operate on the image using the methods/interfaces that Pillow created to make your life easier (save, crop, copy, get size, convert to array, etc).

→ More replies (2)

24

u/abdeljalil73 Mar 24 '21

Can't even imagine that they considered doing it manually in the first place.

13

u/[deleted] Mar 24 '21

There are so many things they do manually that could be automated - but I have been told that you cannot automate design... so sometimes I just leave it. But today I couldn't. I knew Python could do this. Too much of an eager beaver!

6

u/OutlawBlue9 Mar 24 '21

You can automate some design. I worked in a custom graphics print shop and managed to automate the bulk of work using Aleyant software, specifically tFlow. As long as you have predefined outputs that you're looking for it can do a lot of the work for you.

If customers are asking for actual design work instead of here's a picture,. Put it on your product then yeah that's a bit harder but I dont consider the 756 picture resiZe job "design" work and that can totally be automated.

292

u/hassium Mar 24 '21

They asked how. I gave them the answer

You FOOL! Now our secret is out!

167

u/[deleted] Mar 24 '21

I know right, write code, run code, go for an ice cream, watch a movie, send work 6 hours later, still a hero.

12

u/[deleted] Mar 24 '21

Damn! I didn't think of this

12

u/randiesel Mar 25 '21

You will think of it for the rest of your tenure at the company.

Here's the trouble. Non-technical people don't understand the difference between something relatively simple, like what you did, and something complicated. To them, you're a wizard and everything is easy.

Now you're going to get all the crappy boring tasks, OR, people are going to resent you for not doing all the crappy boring tasks.

Plus, you showed them it was only 12 lines of code. Non-technical people don't understand that those 12 lines of code take way longer than just typing 12 sentences on a page. They think writing 100 lines of code should take the same amount of time as a few paragraphs.

It's a sketchy sketchy hole when you try to show non-technical people how you do technical things.

61

u/Synicull Mar 24 '21

I have a 55+ client that I work with a lot that makes me look amazing to my team, most of whom don't code.

My latest question was to find out which of his 100 datasets had a specific field in them.

2 for loops later I'm the messiah.

15

u/[deleted] Mar 24 '21

Loop hero!

38

u/[deleted] Mar 24 '21

Just run that shit raw in command line.

20

u/not-youre-mom Mar 24 '21

You have to assert dominance.

8

u/toyg Mar 24 '21

2 for loops later I'm the messiah.

Nah, you’re just a naughty boy!

47

u/saltedjello Mar 24 '21

"Hey boss, I knew this was important for the company so I pulled an all-nighter and made it happen. Please, I'm not a hero, just doing what's best for the company. But yea, do remember this when performance reviews are due."

4

u/FREE-AOL-CDS Mar 24 '21

“That sounds scary we’ll just let you handle it”

1

u/FruityWelsh Mar 24 '21

I've tried, maybe it's just the fields I've worked in, but there can be an absolute fear to learn a new subject/skill sometimes.

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

6

u/[deleted] Mar 24 '21

Yeah, I've opened pandora's box... or is it python's box?

9

u/luciusan1 Mar 24 '21

Thats exactly what i am at my company.

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

4

u/taughta Mar 24 '21

It would take hours for me too. Still a huge win compared to a whole week.

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.

  1. Open browser

  2. Go to favorite search engine

  3. Search for "how to bulk resize image"

  4. Profit ( ͡° ͜ʖ ͡°)???

1

u/lonelydata Mar 25 '21

I'm not surprised in the slightest, tbh.

2

u/JadendayZero Mar 25 '21

Same, I work at a small legacy company and they still manually punch in a bunch of stuff because the owner doesn't like change or care for new technology

2

u/thatrandomnpc It works on my machine Mar 25 '21 edited Mar 25 '21

You should show your boss how small automations can improve quality of work and inturn bring more productivity, work and revenue.

Here's my first automation story from back when I first started working. Not python at all, but somewhat relevant. Bit of a long story, here it goes..

It was an analytics, etl and data warehousing firm, and once in a month the support team would get data files from various sources and they had to do bit of excel work and verify data from many dashboards and compile KPIs to generate a report to present it to the higher ups. The person who's doing this would be busy for the better part of the day and they have been doing this every month for the past 5-6 years at the time. Wherever they find some strange numbers they do some preliminary analysis and raise bugs with the dev team. This would delay the reports to be sent until the bug is fixed.

This is how I actually came to know about this whole process when a bug was assigned to me. When i checked the db everything seems normal and on futher investigation, I found the person had actually copied the wrong files into the wrong excel sheet. Eh this is human error I thought and closed the bug. Until the checked reports for the bugs raised, and found out it's a common occurrence.

Like the lazy person I am who doesn't want to go through the whole manual process to find bugs which doesn't exist. I spoke with my lead and developed a workflow in my free time, which would do all the manual stuff, mixing and matching and compiling and loaded the results into a table. Made a frontend dashboards where us devs can monitor those compiled KPIs. We eventually tested it properly and released it to the support team.

This saved a lot of unnecessary hiccups in generating the reports for the higher ups, reduced bugs raised and ended up increasing the data quality.

When I asked why this was not done in the past 5 years, the devs were busy with other active dev work and didn't get any request from the support team for automating it. The support team on the other hand were getting billed for the manual work they were doing.

And I was like ok ಠಿ_ಠ, did I actually reduce the billing the support team gets. Actually not, the support team were getting time to work on other support issues.

Anyhow most of the devs and support people were happy and the higher ups were happy they were getting reports on time ¯_(ツ)_/¯

2

u/JadendayZero Mar 25 '21

This is a good example of helping out and working for you in the end but a lot of the times I see that if you go beyond your job description to do technical stuff they'll expect you to be this "wizard" who can do anything and expect to pay you the same regardless of your technical skills. Which imo demotivates anyone from going above and beyond

2

u/thatrandomnpc It works on my machine Mar 25 '21

That's true. That's when you move on to better things when there is not enough stimulation or motivation :)

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:

for f in *.jpg; do convert "$f" -resize 150x150 "$f"; done

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):

for f in *.jpg; do convert "$f" -resize 150x150 "output/$f"& done

6

u/shuttup_meg Mar 24 '21 edited Mar 24 '21

If it could be made more efficient, let me know!

How about something like this:

from multiprocessing import Pool
from PIL import Image
import os

def doit(f):
    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))

if __name__ == "__main__":
    with Pool(4) as p:
        p.map(doit, [f for f in os.listdir('Input') if f.endswith(".jpg")])

2

u/NAG3LT Mar 24 '21 edited Mar 24 '21

On Windows the last part has to be under

if __name__ == '__main__':
    ...

as multiprocessing on Win doesn't fork, but launches a new instance for each process.

BTW need to check if PIL releases GIL, as that would allow to just use multithreading for extra performance.

3

u/shuttup_meg Mar 24 '21

Good call! Edited.

1

u/DuckSaxaphone Mar 25 '21

Absolutely love the style of someone hearing "make this code more efficient" and thinking "OPs probably got at least four cores right?".

2

u/[deleted] Mar 24 '21

What do you mean by headshot?

9

u/[deleted] Mar 24 '21

A photograph of the person, showing only head and shoulders

3

u/riffito Mar 24 '21

The boring kind, apparently! :-P

0

u/[deleted] Mar 24 '21

[deleted]

6

u/not-youre-mom Mar 24 '21

BOOOM 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.

2

u/[deleted] Mar 25 '21

All I got was a thumbs up emoji

congrats on the $6k. Treat yo' self!

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

2

u/[deleted] Mar 25 '21

This is fantastic - and I wish the designers would dive in to understand every nook and cranny of their software but they don't. I'm glad you showed me this as now I can show them and hopefully they use it!

1

u/JohnLocksTheKey Mar 25 '21

This - don’t let this skill increase the workload and expectations without commensurate pay!

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.endswith and the like:

import glob
import os

for filename in glob.glob("Input/*.jpg"):
    # Do stuff

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:

import pathlib
from PIL import Image

for filepath in pathlib.Path('Input').glob('*.jpg):
    im = Image.new('RGB', (150, 150), (255,255,255))
    im2 = Image.open(filepath)
    im2 = im2.convert("L")
    width, height = im2.size
    im.paste(im2, (int((150 - width) / 2), 0))
    im.save(f'Output/{filepath.name}')

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

Pillow

Hmmm?

8

u/caladan84 Mar 24 '21

Maintained fork of the unmaintained PIL.

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?

2

u/onksk Mar 25 '21

Seems to create a new white(RGB: 255,255,255) 150x150 image

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

Python baby 😎

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/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/pag07 Mar 25 '21

If you look closely it is not an f String.

But I agree f strings would have been much easier in that place.

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 => final
im2 => source f => source_file

I'd also create a function for the actual operation, so you can separate IO from actual operations.

def process(source):
    final = Image.new('RGB', (150, 150), (255,255,255))
    source = source.convert("L")
    width, height = source.size
    final.paste(source, (int((150 - width) / 2), 0))
    return final


for file in [file for file in os.listdir('Input') if file.endswith('.jpg']:
    source = Image.open(f'Input/{file}')
    final = process(source)
    final.save(os.path.join('Output', file))

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?

3

u/[deleted] Mar 24 '21

It converts the image to black and white

5

u/TravisJungroth Mar 24 '21

This is why letter code arguments are so dumb.

2

u/No_Conference_5257 Mar 25 '21

PIL: “RGB is for red green blue, it’s a color image”

Me: cool

PIL: “L is for black/white”

Me: ...

2

u/onksk Mar 25 '21

To make it even better, in the printing industry black is considered K

-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.

3

u/[deleted] Mar 24 '21

It was just 8 seconds to run!

→ More replies (2)

0

u/[deleted] Mar 24 '21

[deleted]

→ More replies (1)

730

u/[deleted] Mar 24 '21 edited Sep 30 '26

[removed] — view removed comment

296

u/[deleted] Mar 24 '21

they don't really like automation that much - they fear it will put them out of work! But I guess they'll have embrace it for the mundane jobs like this

42

u/d64 Mar 24 '21

You know how consulting companies that have done some kind of a job many times before will bill a customer say 40 hours for doing it, even though it might take them only 6 hours to do, because of their expertise?

Employees can and should do the same. Say this job was said to take days. Tell you will do it, then write the script or use Photoshop batches or whatever, be done in 45 minutes. Then spend the rest of the day on your own projects, then report triumphantly that you managed to pull it off in just one day. You are seen as efficient, but you are not shooting yourself in the foot by revealing the job can actually be done in no time at all.

22

u/[deleted] Mar 24 '21

It's not my main job - I'm a job coordinator so I handle the requests for work. I just program on the side for fun and wanted to help out. I guess I need to be careful it doesn't open a door for them to request more of this and I land myself in a hole!

→ More replies (1)
→ More replies (4)

334

u/cbunn81 Mar 24 '21 edited Mar 24 '21

Better they do the automation themselves rather than wait around for clients to leave for another company that uses automation.

44

u/[deleted] Mar 24 '21

Code for designers!

→ More replies (4)

9

u/XecutionerNJ Mar 25 '21

Yeah, Apple made the iPhone because the nokia and sony Ericsson phones were getting to be really good ipods and would destroy apples product line.

When others are innovating you out of work, you have to get on the innovation side and kick yourself out of work. Either that or wait for obsolescence.

→ More replies (3)
→ More replies (2)

40

u/beisenhauer Mar 24 '21

Automate the boring stuff, amiright?

→ More replies (1)
→ More replies (38)

57

u/killersquirel11 Mar 24 '21

It'd also be approachable with imagemagick and some bash fu

16

u/riffito Mar 24 '21

With IrfanView on Windows (or Wine) you could do it from a GUI.

IrfanView... the only software that I never changed for anything else since 1997.

→ More replies (3)

13

u/lolinux Mar 24 '21

This was exactly my thought! However, since OP is attracted to Python, I can only cheer! You usually use the tools you know and trust best for the task you have at hand!

→ More replies (1)
→ More replies (2)

6

u/SecretAtLarge Mar 24 '21

Whatever they are, we all have learned they cant google if their life (or career) depended on it.

2

u/Pr0ducer Mar 24 '21

Bulk actions are the commercial photographer's best friend. I can't believe more people don't use them. But with python ... whole new ball game.

→ More replies (6)

9

u/[deleted] Mar 24 '21

[removed] — view removed comment

4

u/flipmcf Mar 24 '21

Adoption is slow. I only started using them a few months ago.

Let’s see how long it takes pythonistas to use the switch statement.

→ More replies (2)

2

u/DuckSaxaphone Mar 25 '21

f-strings have changed my life. I've worked with so many languages but the ability to write something like

print(f" {big_float : .2e}")

So easily is a game changer.

Although my second most used language is Fortran so I'm easily impressed by nice string operations.

0

u/[deleted] Mar 25 '21

[deleted]

2

u/JadendayZero Mar 25 '21

Literally me rn lol