Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

edit rgb values in a jpg with python

I am trying to change the RGB values in a photo with the Python Imaging Library. I have been using the function Image.point and it does what I want except I want to be able to implement a different function on the R the G and the B values. Anyone know how I can do this?

Thanks!

like image 484
clifgray Avatar asked May 30 '12 22:05

clifgray


People also ask

How do I change the RGB color in python?

# In Python, colors can just be stored as 3-Tuples of (Red, Green, Blue). red = (255,0,0) green = (0,255,0) blue = (0,0,255) # Many libraries work with these. # You can also, of course, define your own functions to work with them.

Is there a RGB function in Python?

colors. to_rgb() function is used convert c (ie, color) to an RGB color. It converts the color name into a array of RGB encoded colors. It returns an RGB tuple of three floats from 0-1.

How do you change the image Hue in Python?

The image hue is adjusted by converting the image to HSV (Hue, Saturation, Value) and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode.


1 Answers

You're better off using numpy in addition to PIL for doing math of the individual bands of an image.

As a contrived example that is not meant to look good in any way:

import Image
import numpy as np

im = Image.open('snapshot.jpg')

# In this case, it's a 3-band (red, green, blue) image
# so we'll unpack the bands into 3 separate 2D arrays.
r, g, b = np.array(im).T

# Let's make an alpha (transparency) band based on where blue is < 100
a = np.zeros_like(b)
a[b < 100] = 255

# Random math... This isn't meant to look good...
# Keep in mind that these are unsigned 8-bit integers, and will overflow.
# You may want to convert to floats for some calculations.
r = (b + g) * 5

# Put things back together and save the result...
im = Image.fromarray(np.dstack([item.T for item in (r,g,b,a)]))

im.save('output.png')

Input enter image description here


Output enter image description here

like image 161
Joe Kington Avatar answered Oct 12 '22 23:10

Joe Kington