技术学习笔记之 PIL 模块
1. 导入模块
1
from PIL import Image
2. 打开图片
1
fn = Image.open("tiger.jpg")
3. 获取图像属性
1
2
3
4
5
a = fn.size # (width, height) 元组
a = fn.width # 宽度
a = fn.height # 高度
a = fn.mode # 模式:RGB 彩色、L 灰度、P 256色、1 黑白色
a = fn.format # 图片格式:jpg, png, bmp ……
4. 对图像进行处理
1
2
3
4
5
6
fn = fn.rotate(-90) # 角度制;逆时针旋转
fn = fn.resize((fn.width//2, fn.height//2)) #
fn = fn.show() # 显示图像
fn = fn.convert("L") # 转换模式
fn.save("test.bmp") # 保存图像,自动匹配格式
fn.close() # 关闭图像
5. 像素操作
1
2
3
4
5
pix = fn.load() # 获取全部像素
tpix = pix[i, j] # 获取像素点,其类型取决于图片模式
R, G, B = fn.getpixel((i, j)) # 直接获取像素
new_img.putpixel((i, j), new_pixel) # 写入像素
new_pixel = int(0.299*R + 0.857*G + 0.144*B) # RGB转灰度
6. 示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# convert_manually.py
from PIL import Image
img = Image.open("tiger.jpg")
pix = img.load()
THERESHOLD = 132
new_img = Image.new("L", img.size) # create a blank image in gray mode
new_img2 = Image.new("1", img.size) # create a blank image in 0/1 mode
x, y = img.size
for i in range(x):
for j in range(y):
R, G, B = img.getpixel((i, j))
new_pixel = int(0.299*R + 0.857*G + 0.144*B) # convert to gray mode
new_img.putpixel((i, j), new_pixel) # put a pixel in gray mode
new_img2.putpixel((i, j), (0 if new_pixel < THERESHOLD else 1))
new_img.save("tiger_L.jpg")
new_img2.save("tiger_1.jpg")
new_img.close()
new_img2.close()
img.close()
原图:
灰度:
单色:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# make_frames.py
from PIL import Image
for THERESHOLD in range(0, 256):
img = Image.open("tiger.jpg")
pix = img.load()
new_img2 = Image.new("1", img.size) # create a blank image in 0/1 mode
x, y = img.size
for i in range(x):
for j in range(y):
R, G, B = img.getpixel((i, j))
new_pixel = int(0.299*R + 0.857*G + 0.144*B) # convert to gray mode
new_img2.putpixel((i, j), (0 if new_pixel < THERESHOLD else 1))
new_img2.save("./output/{}.jpg".format(THERESHOLD))
new_img2.close()
img.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# identification_of_coating_cards.py
from PIL import Image
img = Image.open("one-bw.png")
width, height = img.size
RATE = 0.64
cnt = 0
for i in range(width):
for j in range(height):
# print(img.getpixel((i, j)))
if(img.getpixel((i, j)) != 255):
cnt += 1
print(cnt, width*height*RATE)
if(cnt > width*height*RATE):
print("FILLED.")
else:
print("UNFILLED.")
本文由作者按照
CC BY 4.0
进行授权