pip install pillow
from PIL import Image
img_origin = Image.open('sample.jpg')
img = img_origin.copy()
img
img.size
img_gray = img.convert('L')
img_gray.save('sample_gray.jpg')
img_gray
img.rotate(45)
img.crop((100, 50, 700, 150))
img.getpixel((1, 1)) #(w, h)
%matplotlib inline
import matplotlib.pyplot as plt
pixel_count = img.histogram()
R_count = pixel_count[:256]
G_count = pixel_count[256:2*256]
B_count = pixel_count[2*256:3*256]
plt.figure(1)
plt.subplot(311)
plt.bar([i for i in range(256)], R_count, 1, color='red')
plt.subplot(312)
plt.bar([i for i in range(256)], G_count, 1, color='green')
plt.subplot(313)
plt.bar([i for i in range(256)], B_count, 1, color='blue')
def f(x):
if x < 30:
return 0
if x > 225:
return 255
return (x-30) / (225 - 30) * 255
img = img_origin.copy()
W, H = img.size
for w in range(W):
for h in range(H):
r, g, b = img.getpixel((w, h))
r = int(f(r))
g = int(f(g))
b = int(f(b))
img.putpixel((w, h), (r, g, b))
img
pixel_count = img.histogram()
R_count = pixel_count[:256]
G_count = pixel_count[256:2*256]
B_count = pixel_count[2*256:3*256]
plt.figure(1)
plt.subplot(311)
plt.bar([i for i in range(256)], R_count, 1, color='red')
plt.subplot(312)
plt.bar([i for i in range(256)], G_count, 1, color='green')
plt.subplot(313)
plt.bar([i for i in range(256)], B_count, 1, color='blue')
對 rgb 都做「開根號 * 16」的運算
int(根號(0) * 16) = 0
int(根號(255) * 16) = 255
經過運算之後還會在 0~255 的範圍內
def f2(x):
return int((x ** 0.5) * 16)
img = img_origin.copy()
W, H = img.size
for w in range(W):
for h in range(H):
r, g, b = img.getpixel((w, h))
r = f2(r)
g = f2(g)
b = f2(b)
img.putpixel((w, h), (r, g, b))
img
pixel_count = img.histogram()
R_count = pixel_count[:256]
G_count = pixel_count[256:2*256]
B_count = pixel_count[2*256:3*256]
plt.figure(1)
plt.subplot(311)
plt.bar([i for i in range(256)], R_count, 1, color='red')
plt.subplot(312)
plt.bar([i for i in range(256)], G_count, 1, color='green')
plt.subplot(313)
plt.bar([i for i in range(256)], B_count, 1, color='blue')
def f2(x):
return int((x ** 0.5) * 16)
def f3(x):
if x < 100:
return 0
return int((x-100) / (255-100) * 255)
im = img_origin.copy()
W, H = img.size
for w in range(W):
for h in range(H):
r, g, b = img.getpixel((w, h))
r = f3(f2(r))
g = f3(f2(g))
b = f3(f2(b))
img.putpixel((w, h), (r, g, b))
img
pixel_count = img.histogram()
R_count = pixel_count[:256]
G_count = pixel_count[256:2*256]
B_count = pixel_count[2*256:3*256]
plt.figure(1)
plt.subplot(311)
plt.bar([i for i in range(256)], R_count, 1, color='red')
plt.subplot(312)
plt.bar([i for i in range(256)], G_count, 1, color='green')
plt.subplot(313)
plt.bar([i for i in range(256)], B_count, 1, color='blue')
from PIL import ImageEnhance
img = img_origin.copy()
enhancer = ImageEnhance.Contrast(img)
enhancer.enhance(1)
enhancer.enhance(1.5)
enhancer.enhance(2)
enhancer = ImageEnhance.Color(img)
enhancer.enhance(0.7)
enhancer.enhance(1.3)
enhancer = ImageEnhance.Brightness(img)
enhancer.enhance(0.7)
enhancer.enhance(1.3)