import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
# 边里该文件夹下的文件名称
def read_directory(directory_name):
file_list = []
for filename in os.listdir(directory_name):
str = directory_name+'/'+filename
file_list.append(str)
return file_list
def divide_method1(img,m,n):#分割成m行n列
print(img.shape)
h, w = img.shape[0],img.shape[1]
gx = np.round(h).astype(np.int)
gy = np.round(w).astype(np.int)
divide_image = np.zeros([m-1, n-1, int(h*1.0/(m-1)+0.5), int(w*1.0/(n-1)+0.5),3], np.uint8)#这是一个五维的张量,前面两维表示分块后图像的位置(第m行,第n列),后面三维表示每个分块后的图像信息
for i in range(m-1):
for j in range(n-1):
print(i)
print(j)
#这样写比a[i,j,...]=要麻烦,但是可以避免网格分块的时候,有些图像块的比其他图像块大一点或者小一点的情况引起程序出错
print(img[gy[i][j]:gy[i+1][j+1], gx[i][j]:gx[i+1][j+1],:])
divide_image[i,j,0:gy[i+1][j+1]-gy[i][j], 0:gx[i+1][j+1]-gx[i][j],:]= img[gy[i][j]:gy[i+1][j+1], gx[i][j]:gx[i+1][j+1],:]
return divide_image
def divide_method2(img,m,n):#分割成m行n列
h, w = img.shape[0],img.shape[1]
grid_h=int(h*1.0/(m-1)+0.5)#每个网格的高
grid_w=int(w*1.0/(n-1)+0.5)#每个网格的宽
#满足整除关系时的高、宽
h=grid_h*(m-1)
w=grid_w*(n-1)
#图像缩放
img_re=cv2.resize(img,(w,h),cv2.INTER_LINEAR)# 也可以用img_re=skimage.transform.resize(img, (h,w)).astype(np.uint8)
#plt.imshow(img_re)
gx, gy = np.meshgrid(np.linspace(0, w, n),np.linspace(0, h, m))
gx=gx.astype(np.int_)
gy=gy.astype(np.int_)
divide_image = np.zeros([m-1, n-1, grid_h, grid_w,3], np.uint8)#这是一个五维的张量,前面两维表示分块后图像的位置(第m行,第n列),后面三维表示每个分块后的图像信息
for i in range(m-1):
for j in range(n-1):
divide_image[i,j,...]=img_re[
gy[i][j]:gy[i+1][j+1], gx[i][j]:gx[i+1][j+1],:]
return divide_image
def save_blocks(title,divide_image):#
m,n=divide_image.shape[0],divide_image.shape[1]
for i in range(m):
for j in range(n):
plt.imshow(divide_image[i,j,:])
plt.axis('off')
plotPath= str(title)+"+"+str(i)+str(j)+'.jpg' # 图片保存路径
plt.savefig("./img_list/"+plotPath)
if __name__ == '__main__':
intput = read_directory("./img_total")
print("图片共有:",len(intput))
title = 1
print("==============开始分块处理文件夹内的图片==============")
for input_path in intput:
print("开始处理第",title,"个,其地址为:",input_path)
img = cv2.imread(input_path) # 图片地址
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
h, w = img.shape[0], img.shape[1]
m = 4
n = 4
divide_image2=divide_method2(img,m+1,n+1) #该函数中m+1和n+1表示网格点个数,m和n分别表示分块的块数
save_blocks(title,divide_image2)
print("第", title, "个已分块完毕")
print("-----------------------------")
title += 1
print("==============完成全部分块处理文件夹的图片==============")