lwf
lwf

Reputation: 85

Python -- change the RGB values of the image and save as a image

I can read every pixel' RGB of the image already, but I don't know how to change the values of RGB to a half and save as a image.Thank you in advance.

from PIL  import *

def half_pixel(jpg):
  im=Image.open(jpg)
  img=im.load()
  print(im.size)
  [xs,ys]=im.size  #width*height

# Examine every pixel in im
  for x in range(0,xs):
     for y in range(0,ys):
        #get the RGB color of the pixel
        [r,g,b]=img[x,y] 

Upvotes: 1

Views: 25530

Answers (4)

user10263606
user10263606

Reputation: 51

  • get the RGB color of the pixel

    [r,g,b]=img.getpixel((x, y))
    
  • update new rgb value

     r = r + rtint
     g = g + gtint
     b = b + btint
     value = (r,g,b)
    
  • assign new rgb value back to pixel

    img.putpixel((x, y), value)
    

Upvotes: 4

Frederik Kratzert
Frederik Kratzert

Reputation: 166

If you have Numpy and Matplotlib installed, one solution would be to convert your image to a numpy array and then e.g. save the image with matplotlib.

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

img = Image.open(jpg)
arr = np.array(img)
arr = arr/2 # divide each pixel in each channel by two 
plt.imsave('output.png', arr.astype(np.uint8))

Be aware that you need to have a version of PIL >= 1.1.6

Upvotes: 0

Hal Jarrett
Hal Jarrett

Reputation: 835

You can do everything you are wanting to do within PIL.

If you are wanting to reduce the value of every pixel by half, you can do something like:

import PIL

im = PIL.Image.open('input_filename.jpg')
im.point(lambda x: x * .5)
im.save('output_filename.jpg')

You can see more info about point operations here: https://pillow.readthedocs.io/en/latest/handbook/tutorial.html#point-operations

Additionally, you can do arbitrary pixel manipulation as: im[row, col] = (r, g, b)

Upvotes: 1

Håken Lid
Håken Lid

Reputation: 23064

There are many ways to do this with Pillow. You can use Image.point, for example.

# Function to map over each channel (r, g, b) on each pixel in the image
def change_to_a_half(val):
    return val // 2

im = Image.open('./imagefile.jpg')
im.point(change_to_a_half)

The function is actually only called 256 times (assuming 8-bits color depth), and the resulting map is then applied to the pixels. This is much faster than running a nested loop in python.

Upvotes: 1

Related Questions