图片裁剪

python中有较方便的包,可以直接裁剪图片,将一张大图裁剪成多张小图



# This is a sample Python script.

import glob

# Press Shift+F10 to execute it or replace it with your code.

# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import math, shutil

import os.path

import cv2

from PILimport Image

def cut_panorama(name, order):

img = cv2.imread(name)

print(type(img.shape))

# 将该图片分成4行8列

    x_cut = img.shape[0] /4  # *0.72

    y_cut = img.shape[1] /8

    # 输出当前像素

    print(x_cut)

print(y_cut)

n =0

    path ='C:/Users/xiekaixuan/PycharmProjects/pythonProject/output/'

    for iin range(4):

for jin range(8):

xs =int(i * x_cut)

xe =int((i +1) * x_cut)

ys =int(j * y_cut)

ye =int((j +1) * y_cut)

cropped = img[xs:xe, ys:ye]# 裁剪坐标为[y0:y1, x0:x1]

            print('n转换前:', n)

# 前方高能,序号转换

            if 0 <= n %8 <4:

m = n +4

            else:

m = n -4

            print('n转换后:', m)

# 如果序号不到10,要补足两位

            num ='0' if m <10 else ''

            mt = math.pow(10, 5 -len(str(order)))

begin_num =str(int(mt))[1:]

filename = begin_num +str(order) +'-pano-tex-r0-' + num +str(m) +'.jpg'

            print('fileName:', filename)

cv2.imwrite(os.path.join(path, filename), cropped)

n +=1

    print(f'Hi, finished')# Press Ctrl+F8 to toggle the breakpoint.

# 更改当前文件夹内所有jpg的分辨率

def convertjpg(jpgfile, k):

img = Image.open(jpgfile)

resolution =int(math.pow(2, k +7))# 当前分辨率

    new_img = img.resize((resolution, resolution), Image.ANTIALIAS)

new_img.save(os.path.join("output/r" +str(k), os.path.basename(jpgfile)))

# number = os.getcwd()

# cn = len(os.listdir(number))

    # print('*****************当前文件夹目录下文件数量:', cn)

    # 图片重命名

    sonFolder = jpgfile.split('\\')

newOrder =int(sonFolder[1].split('-')[0]) //100

    dstFileFront = sonFolder[0] +'\\r' +str(k) +'\\'

    newFolder(dstFileFront +str(newOrder))

dstFileMiddle =str(newOrder) +'\\' + sonFolder[1].split('r')[0] +'r' +str(k) +'-'

    dstFileBack = jpgfile.split('-')[4]

os.rename(sonFolder[0] +'\\r' +str(k) +'\\' + sonFolder[1], dstFileFront + dstFileMiddle + dstFileBack)

def newFolder(filepath):

folder = os.path.exists(filepath)

if not folder:

os.makedirs(filepath)

print(filepath, " has been created!")

# def movePics():

if __name__ =='__main__':

# step1: 将每个大图切割成32个小图,并按照统一格式命名存放

    # order = 0

# for pa_pic in glob.glob("panorama/*.jpg"):

#    cut_panorama(pa_pic, order)

#    order += 1

    # step2: 新建4个文件夹,r0,r1,r2,r3;分别存放不同分辨率的图片

    for jpgfilein glob.glob("output/*.jpg"):

for iin range(4):

newFolder('C:/Users/xiekaixuan/PycharmProjects/pythonProject/output/r' +str(i))

convertjpg(jpgfile, i)

# step3: 将r文件夹中的各图片分文件夹存放,每m个图片存放一个文件夹

    # number = os.getcwd()

    # cn = len(os.listdir(number))

你可能感兴趣的:(图片裁剪)