[英]Changing pixels to grayscale using PIL in Python
I am trying to convert a RGB picture to grayscale. 我正在尝试将RGB图片转换为灰度。 I do not want to use image.convert('L').
我不想使用image.convert('L')。 This just shows the original image without changing anything.
这只是显示原始图像而没有任何更改。 I have tried putting different numbers in the 'red,green,blue=0,0,0' line which does change the color of the image but it is not what I want.
我尝试在'red,green,blue = 0,0,0'行中放入不同的数字,这确实会改变图像的颜色,但这不是我想要的。
import PIL
from PIL import Image
def grayscale(picture):
res=PIL.Image.new(picture.mode, picture.size)
width, height = picture.size
for i in range(0, width):
for j in range(0, height):
red, green, blue = 0,0,0
pixel=picture.getpixel((i,j))
red=red+pixel[0]
green=green+pixel[1]
blue=blue+pixel[2]
avg=(pixel[0]+pixel[1]+pixel[2])/3
res.putpixel((i,j),(red,green,blue))
res.show()
grayscale(Image.show('flower.jpg'))
import PIL
from PIL import Image
def grayscale(picture):
res=PIL.Image.new(picture.mode, picture.size)
width, height = picture.size
for i in range(0, width):
for j in range(0, height):
pixel=picture.getpixel((i,j))
avg=(pixel[0]+pixel[1]+pixel[2])/3
res.putpixel((i,j),(avg,avg,avg))
res.show()
image_fp = r'C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg'
im = Image.open(image_fp)
grayscale(im)
The mistake you are doing is you are not updating the pixel values with grayscale values. 您所做的错误是您没有使用灰度值更新像素值。 Gray is calculated by averaging R, G, B values.
通过计算R,G,B值的平均值来计算灰度。
You can replace with this in grayscale function: 您可以在灰度函数中替换为:
def grayscale(picture):
res=PIL.Image.new(picture.mode, picture.size)
width, height = picture.size
for i in range(0, width):
for j in range(0, height):
pixel=picture.getpixel((i,j))
red= pixel[0]
green= pixel[1]
blue= pixel[2]
gray = (red + green + blue)/3
res.putpixel((i,j),(gray,gray,gray))
res.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.