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

雨燕双飞 提交于 2019-12-18 09:24:02

问题


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] 

回答1:


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)




回答2:


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.




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/49280402/python-change-the-rgb-values-of-the-image-and-save-as-a-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!