hirose's page

ライブラリ無しでPythonで画像モノクロ化

ライブラリ(PIL,numpy)を使い,最低限のコードを作る

まずはできあがったプログラムと環境を

Windows11環境,Python 3.10.6

from PIL import Image
import numpy as np
img = Image.open('original.jpg')
width, height = img.size
img2 = Image.new('RGB', (width, height))
img_pixels = []
for y in range(height):
  for x in range(width):
    img_pixels.append(img.getpixel((x,y)))
img_pixels = np.array(img_pixels)
for y in range(height):
  for x in range(width):
    # aa=int((img_pixels[y*width+x][0]+img_pixels[y*width+x][1]+img_pixels[y*width+x][2])/3)
    X = 2.2
    aa = int(((0.222015*img_pixels[y*width+x][0])**X + (0.706655*img_pixels[y*width+x][1])**X + (0.071330*img_pixels[y*width+x][2])**X)**(1/X))
    img2.putpixel((x,y), (aa,aa,aa))
img2.show()