欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

批量随机裁剪图片 python pil

程序员文章站 2024-02-13 16:56:34
...
#coding=utf-8

import cv2
import random
import os
import numpy as np
from tqdm import tqdm

def solve():
	cur_src="E:/CCF_competition/remote_sensing_image/unet_buildings/unet_buildings/newsrc/jpg/"
	cur_label="E:/CCF_competition/remote_sensing_image/unet_buildings/unet_buildings/newlabel/"
	for i in range(1,2):
		count = 1
		cur_url="{}{}.jpg".format(cur_src,i)
		cur_url_label = "{}{}.png".format(cur_label,i)
		print(cur_url)
		now = cv2.imread(cur_url)
		now_label = cv2.imread(cur_url_label)
		w,h,_ = now.shape
		for k in range(w//256):
			for kk in range(h//256):
				s_img = now[k*256:(k+1)*256,kk*256:(kk+1)*256,:]
				l_img = now_label[k*256:(k+1)*256,kk*256:(kk+1)*256,:]
				cv2.imwrite("{}{}/{}_{}.jpg".format(cur_src,"cut",i,count),s_img)
				cv2.imwrite("{}{}/{}_{}.png".format(cur_label,"cut",i,count),l_img)
				count +=1
		while count<=2500:
			j = random.randint(0,5)
			if j<=3:
				x_min=random.randint(0,w-512)
				y_min=random.randint(0,h-512)
				s_img = now[x_min:x_min+512,y_min:y_min+512,:]
				l_img = now_label[x_min:x_min+512,y_min:y_min+512,:]
				cv2.imwrite("{}{}/{}_{}.jpg".format(cur_src,"cut",i,count),s_img)
				cv2.imwrite("{}{}/{}_{}.png".format(cur_label,"cut",i,count),l_img)	
			else:
				x_min=random.randint(0,w-1024)
				y_min=random.randint(0,h-1024)
				s_img = now[x_min:x_min+1024,y_min:y_min+1024,:]
				l_img = now_label[x_min:x_min+1024,y_min:y_min+1024,:]
				cv2.imwrite("{}{}/{}_{}.jpg".format(cur_src,"cut",i,count),s_img)
				cv2.imwrite("{}{}/{}_{}.png".format(cur_label,"cut",i,count),l_img)
			count += 1
if __name__ == '__main__':
	solve()