大小不够1024的,填充为黑色import os
import numpy as np
import cv2 as cv
import PIL.Image as Image
def cutting(img_path, data_path,image_name, clip_path):
"""
:param img_path: 图片文件夹
:param data_path: 数据文件夹
:param image_name: 切割原始图片名
:param clip_path: 切割图片保存路径
:return:
"""
img_size = 1024
n, m, max_n = 0, 0, 0
img = cv.imread(os.path.join(img_path, image_name), 1)
clip_img_path = os.path.join(data_path, 'clip', clip_path)
if not os.path.exists(clip_img_path):
os.makedirs(clip_img_path)
h, w = img.shape[0], img.shape[1]
for i in range(0, h, img_size):
img_h = (h % img_size) if (i + img_size) > h else 1024
for j in range(0, w, img_size):
max_n = n if max_n <= n else max_n
end_i, end_j = min(h, i + img_size), min(w, j + img_size)
cropped = img[i:end_i, j:end_j]
img_w = (w % img_size) if (j + img_size) > w else 1024
img_orig = Image.fromarray(cv.cvtColor(cropped, cv.COLOR_BGR2RGB))
to_image = Image.new('RGB', (img_size, img_size))
to_image.paste(img_orig, (0, 0))
if img_w != 1024:
img_w_new = np.zeros(shape=((img_size - img_w), img_h, 3), dtype=np.uint8)
img_w_new = Image.fromarray(img_w_new)
to_image.paste(img_w_new, (img_w, 0))
if img_h != 1024:
img_h_new = np.zeros(shape=(img_size, (img_size - img_h), 3), dtype=np.uint8)
img_h_new = Image.fromarray(img_h_new)
to_image.paste(img_h_new, (0, img_h))
to_image.save(clip_img_path + '/' + str(m) + '_' + str(n) + ".jpg")
elif img_w == 1024 and img_h != 1024:
img_h_new = np.zeros(shape=(img_size, (img_size - img_h), 3), dtype=np.uint8)
img_h_new = Image.fromarray(img_h_new)
to_image.paste(img_h_new, (0, img_h))
to_image.save(clip_img_path + '/' + str(m) + '_' + str(n) + ".jpg")
else:
cv.imwrite(clip_img_path + '/' + str(m) + '_' + str(n) + ".jpg", cropped)
n += 1
n = 0
m += 1
if __name__ == '__main__':
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
data_path = os.path.join(root, 'data')
img_path = os.path.join(data_path, 'bhfx1')
cutting(img_path, data_path, "fw1_2021.tif", "clip_2021")