简体   繁体   English

Python —更改图像的RGB值并另存为图像

[英]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. 我已经可以读取图像中每个像素的RGB了,但是我不知道如何将RGB的值更改为一半并另存为图像。在此先感谢您。

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] 

There are many ways to do this with Pillow. 有很多方法可以使用Pillow。 You can use Image.point , for example. 例如,您可以使用Image.point

# 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. 实际上,该函数仅被调用256次(假定8位色深),然后将生成的贴图应用于像素。 This is much faster than running a nested loop in python. 这比在python中运行嵌套循环要快得多。

If you have Numpy and Matplotlib installed, one solution would be to convert your image to a numpy array and then eg save the image with matplotlib. 如果安装了Numpy和Matplotlib,则一种解决方案是将图像转换为numpy数组,然后例如使用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 请注意,您需要的PIL版本> = 1.1.6

You can do everything you are wanting to do within PIL. 您可以在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 您可以在此处查看有关点操作的更多信息: 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) 此外,您可以进行任意像素处理,例如: im[row, col] = (r, g, b)

  • get the RGB color of the pixel 获取像素的RGB颜色

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

      r = r + rtint g = g + gtint b = b + btint value = (r,g,b) 
  • assign new rgb value back to pixel 将新的rgb值分配回像素

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM