0

내가 파이썬 3.4.2에서 그레이 스케일로 이미지를 변환 할 노력하고있어,하지만 난 혼자 "빨간색"픽셀떠나, 픽셀에 의한 그레이 스케일 픽셀 파이썬에서 혼자 한 색상을 PIL 이미지를 변환

두고 싶습니다
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 

지금 당장이 이미지는 회색조로 변환되지만 내가 생각한 것처럼 색이있는 픽셀을 남기지 않는다고 말할 수있는 한, 내 작업을 수행하는 데 도움이되는/제안/다른 방법은 크게 감사하겠습니다.

감사합니다

내가하지 않았기 때문에 누구 때문에

res.putpixel(pixel) 

오류를 던지고 했어야 내 부분에 오류로 내 코드가 작동하지 않는 미래에이를 읽고 그래서 넣다

+0

나는이 지침을 따르려고 노력 :

는 도움을 팀 동료를 묻는 우리는이 내 코드를 변경 반복을 통해 각 픽셀의 getpixel()을 호출하여 색상을 얻습니다. 3 r/g/b를 원하는 색상과 비교하십시오.원하는 색상의 임계 값을 벗어나는 경우 몇 가지 수식을 사용하여 그레이 스케일 (예 : 3 개의 값의 평균을 rgb로 설정)을 사용하고 풋 픽셀을 사용하여 해당 픽셀을 바꿉니다. 이미지 저장 아마 훨씬 더 효율적입니다 방법, 그러나 이것은 당신이 원하는 것을 얻기위한 간단한 방법입니다. –

+0

** 빨간색 ** 픽셀 만 남기고 싶다면 이미지의 ** 빨간색 채널 **을 얻었을 수 있으며이를 임계 값으로 수행 할 수 있습니다. 그런 다음 원래 이미지로 결과 이미지를 마스킹하여 빨간색과 빨간색 픽셀을 모두 얻을 수 있습니다. 이 큰 코드를 작성하지 않아도됩니다. –

답변

0

그것은 픽셀을 색상 정보에 배치하는 위치입니다. 오류가 발생하지 않았기 때문에 실제로 else : statement 안에 들어간 적이 결코 없습니다. 파일 2에서 1 읽기 이미지 :

from numpy import * 
from PIL import Image 

red_lower_threshold = 150 
green_blue_diff_threshold = 50 
def grayscale(picture): 
    res = Image.new(picture.mode, picture.size) 

    for i in range(0, picture.size[0]): 
     for j in range(0, picture.size[1]): 
      pixel = picture.getpixel((i, j)) #get a pixel 
      red = pixel[0] 
      green = pixel[1] 
      blue = pixel[2] 

      if (red > red_lower_threshold and abs(green - blue) < green_blue_diff_threshold): 
       res.putpixel((i, j), pixel) 
      else: 
       avg = (pixel[0] + pixel[1] + pixel[2])/3 
       res.putpixel((i, j), (int(avg), int(avg), int(avg))) 

res.save('output.jpg') 
return res 
이 완벽 하진

그러나 그것의 실행 가능한 솔루션

관련 문제