libvips / pyvips

python binding for libvips using cffi
MIT License
649 stars 50 forks source link

How to find regions of a certain color #124

Open comfortablynick opened 5 years ago

comfortablynick commented 5 years ago

Hello,

Thanks for this library, I'm just getting started with it. I am a photographer and have been trying to write a program to resize/compress/watermark my images.

I first started in C, but switched to Python once I found there was not much of a speed difference. I found this example that I've used to get text watermarking working: https://gist.github.com/jcupitt/db972e738cfacdf8055f

What I'm hoping to do is find out the color of a region so that I know what color to make the watermark/copyright text. Ideally, I'd like to scan the edges of the image to find a dark or light area and then write the text in black or white. I currently have to do this manually in photoshop each time I edit an image, which sucks!

Is anything like this possible with vips?

jcupitt commented 5 years ago

Hello @comfortablynick,

Sure, there are lots of ways of doing this. For example, you could make a text mask, then scan the image and find the average colour of the pixels within the mask. Then invert that (ie. 255 - x) and use that colour for the watermark.

Is this a text overlay in one spot on the image, or are you pasting the text everywhere?

jcupitt commented 5 years ago

I made an example for you:

https://github.com/libvips/pyvips/blob/master/examples/watermark_context.py

It adds a watermark in the bottom left, and automatically picks a contrasting colour. You can use it like this:

$ ./watermark_context.py ~/pics/wtc.jpg x.jpg "hello there!"

You can use markup in the string, for example:

$ ./watermark_context.py ~/pics/k2.jpg x.jpg "<b>HELLO</b> <i>this</i> text is <big>HUGE</big>"

Making:

x

comfortablynick commented 5 years ago

Thanks, that helps a lot!

Here's an example of what it looks like when I try to watermark each corner of an actual image: Sunset

To answer your first question, I'm generally going to be looking for the most appropriate spot along the edge of the image to put the copyright text. The way I do it now is either use black or white depending on whether it's a dark or light area of the photo. So I'll probably need to modify your example to use either 255 or 0 (although the gray in the darker bottom corners looks nice). Using other colors may distract from the image, but I'm not sure.