Python的一些小操作

灵衣玉佩,一阴一阳,罗生堂下,秋兰长生。。。
主要是记录一些学习过程中可能会用到的一些代码:

1、截取单张图片

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from PIL import Image
import os

img = Image.open('home/usrname/picture/1.jpg')		# 读取图片
img_size = img.size
print('图片的宽度和高度分别是{}'.format(img_size))

# 截取一张宽和高均为256的图片
x = 0
y = 0
w = 256
h = 256
new_image = img.crop((x, y, x+w, y+h))

# 保存图片
path = new_image.save('home/usrname/picture/result/1.jpg')

2、批量截取图片

#!/usr/bin/python
# -*- coding:utf-8 -*-

from PIL import Image
import os

a = 1
path = '/home/usrname/picture/'
c= os.listdir(path)

for i in c:
    image_path = path + i
    img = Image.open(image_path)
    img_size = img.size
    print('图片的宽度和高度分别是{}'.format(img_size))
    
    # 截取图片
    x = 0		# 从左往右的距离
    y = 0		# 从上往下的距离
    w = 256		# 截取后的图片的宽度
    h = 256		# 截取后的图片的高度
    new_image = img.crop((x, y, x+w, y+h))
    new_path = os.path.join('result')
    if not os.path.isdir(new_path):
        os.mkdir(new_path)
    save_path = new_path + '/' + str(i)
    p = new_image.save(save_path)
    a = a + 1

暂时就这些,持续更新中。。。

猜你喜欢

转载自blog.csdn.net/weixin_43914756/article/details/84888855