python 实现一张图片的split
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
def get_name(im_path):
im_name = os.path.split(im_path)
name = os.path.splitext(im_name[len(im_name) - 1])
return name[0]
def divide_method1(img, 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)
for i in range(m - 1):
for j in range(n - 1):
print(i)
print(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):
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)
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)
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 display_blocks(divide_image, name, save_dir):
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, :])
plotPath = str(i) + str(j) + name + '.jpg'
cv2.imwrite(save_dir + plotPath, cv2.cvtColor(divide_image[i, j, :], cv2.COLOR_BGRA2GRAY))
if __name__ == '__main__':
save_dir = "F:/rock_data/AI4_process/image_new/"
read_dir = 'F:/rock_data/AI4_process/image/NLA_398919642EDR_F0030078NCAM00300M1.jpg'
name = get_name(read_dir)
img = cv2.imread(read_dir)
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)
fig3 = plt.figure('分块后的子图像:图像缩放法')
display_blocks(divide_image2,name, save_dir)