In: Computer Science
Image conversion code according to above formula is
CODE 1 :
from PIL import Image #using Image from pillow library
def sepia(img_path:str)->Image:
img = Image.open(img_path)
width, height = img.size
pixels = img.load() #creating the pixel map
for y in range(height):
for x in range(width):
r, g, b = img.getpixel((x, y))
new_r = int(0.393 * r + 0.769 * g + 0.189 * b)
new_g = int(0.349 * r + 0.686 * g + 0.168 * b)
new_b = int(0.272 * r + 0.534 * g + 0.131 * b)
if new_r > 255: #r,g,b should not exceed 255
new_r = 255
if new_g > 255:
new_g = 255
if new_b > 255:
new_b = 255
pixels[x, y] = (new_r,new_g,new_b)
return img
You can also use this simple formula instead for conversion (it is simple and effective).
CODE 2 :
from PIL import Image #using Image from pillow library
def sepia(img_path:str)->Image:
img = Image.open(img_path)
width, height = img.size
pixels = img.load() #creating the pixel map
for y in range(height):
for x in range(width):
r, g, b = img.getpixel((x, y))
new_val = (0.3 * r + 0.59 * g + 0.11 * b)
new_r = int(new_val * 2)
if new_r > 255: #r,g,b should not exceed 255
new_r = 255
new_g = int(new_val * 1.5)
if new_g > 255:
new_g = 255
new_b = int(new_val)
if new_b > 255:
new_b = 255
pixels[x, y] = (new_r,new_g,new_b)
return img