Processing an image to sepia tone in Python

后端 未结 2 1098
日久生厌
日久生厌 2021-01-20 16:07

I need help figuring out how to convert an image to sepia. This is what I have so far..but it only changes everything to black and white colors with a very small tint of bro

相关标签:
2条回答
  • 2021-01-20 16:30

    Your gray level image is not a gray level image. In a gray level image all three channels r,g,b have the same value.

    Open paint and try it to verify if your code makes sense.

    Fix these lines:

    newR = (R * 0.393 + G * 0.769 + B * 0.189)
    newG = (R * 0.349 + G * 0.686 + B * 0.168)
    newB = (R * 0.272 + G * 0.534 + B * 0.131)
    

    Simply use the mean of r,g,b and put it into newR, newG and newG.

    There are some weighted means as well. Just Google for RGB to intensity formulas.

    0 讨论(0)
  • 2021-01-20 16:38

    You can convert image to sepia by just manipulating the pixel values. The following is the code(Disclaimer : Taken from this article.)

    from PIL import Image
    
    def sepia(image_path:str)->Image:
        img = Image.open(image_path)
        width, height = img.size
    
        pixels = img.load() # create the pixel map
    
        for py in range(height):
            for px in range(width):
                r, g, b = img.getpixel((px, py))
    
                tr = int(0.393 * r + 0.769 * g + 0.189 * b)
                tg = int(0.349 * r + 0.686 * g + 0.168 * b)
                tb = int(0.272 * r + 0.534 * g + 0.131 * b)
    
                if tr > 255:
                    tr = 255
    
                if tg > 255:
                    tg = 255
    
                if tb > 255:
                    tb = 255
    
                pixels[px, py] = (tr,tg,tb)
    
        return img
    

    Original Image

    Sepia Image

    0 讨论(0)
提交回复
热议问题