0
我試圖將圖像轉換在Python 3.4.2灰度,但我想給所有的「紅」像素單獨在Python由像素灰度像素轉換一個PIL形象,留下獨自1種顏色
from numpy import *
from pylab import *
from PIL import Image
from PIL import ImageOps
def grayscale(picture):
res = Image.new(picture.mode, picture.size)
red = '150,45,45' # for now I'm just tyring
x = red.split(",") # to change pixels with R value less than 150
#and G/B values greater than 45
width, height = picture.size #to greyscale
for i in range(0, width):
for j in range(0, height):
pixel = picture.getpixel((i, j)) #get a pixel
pixelStr = str(pixel)
pixelStr = pixelStr.replace('(', '').replace(')', '')
pixelStr.split(",") #remove parentheses and split so we
#can convert the pixel into 3 integers
#if its not specifically in the range of values we're trying to convert
#we place the original pixel otherwise we convert the pixel to grayscale
if not (int(pixelStr[0]) >= int(x[0]) and int(pixelStr[1]) <= int(x[1]) and int(pixelStr[2]) <= int(x[2])):
avg = (pixel[0] + pixel[1] + pixel[2])/3
res.putpixel((i, j), (int(avg), int(avg), int(avg)))
else:
res.putpixel(pixel)
return res
現在,這將圖像轉換爲灰度,但據我所知,它不會留下像我想的那樣的任何彩色像素,任何幫助/建議/替代方式來完成我的任務將不勝感激。
謝謝
我試圖按照這些方向:從文件 1讀取圖像循環並調用每個像素上的getpixel()以獲取其顏色 3將其r/g/b與您想要的顏色進行比較。如果它落在你想要的顏色的某個 閾值之外,則使用一些公式轉換爲 灰度(例如,將rgb設置爲3個值的平均值),並使用putpixel替換該像素 保存圖像 可能效率更高方式,但這是一個簡單的方法來獲得你想要的。 –
如果你想單獨留下**紅色**像素,你可能已經獲得了圖像的**紅色通道**並對此執行了閾值。然後你可以用你的原稿遮蓋得到的圖像,以獲得全部紅色並接近紅色像素。我不必寫這麼大的代碼 –