文件夹如图所示:
程序:
import os
import cv2
'''
裁剪tiff图为(224,224)
'''
source_dir = 'D:\desk\dm\Acky\BaseNet\data_set\FUSARship-3channel-tiff'
target_dir = 'D:\desk\dm\Acky\BaseNet\data_set\FUSARship-3-tiff'
# 如果目标目录不存在的话,进行目录的新建
if not os.path.exists(target_dir):
os.makedirs(target_dir)
T = os.listdir(source_dir)
for t in T:
files = os.listdir(os.path.join(source_dir, t))
for class_file in files:
image_files = os.listdir(os.path.join(source_dir, t, class_file))
for image in image_files:
image_name = os.path.join(source_dir, t, class_file, image)
image_src = os.path.join(target_dir, t, class_file, image)
img = cv2.imread(image_name)
image = img[144:368, 144:368]
print(image.shape)
if not os.path.exists(os.path.join(target_dir, t, class_file,)):
os.makedirs(os.path.join(target_dir, t, class_file,))
cv2.imwrite(image_src, image) # 图片存储
print("finish" + " " + image_name)
单张图片的测试代码:
import os
import cv2
img = cv2.imread("D:\desk\dm\Acky\BaseNet\data_set\FUSARship-3channel-tiff\\train\cargoship\Ship_C01S07N0001.tiff")
print(img.shape)
cv2.imshow("裁剪后前", img)
# 中心裁剪
# 左上角:144=(512-224)/2 右下角:368=512-144
image = img[144:368, 144:368]
print(image.shape)
cv2.imshow("裁剪后", image)
cv2.waitKey()
cv2.destroyAllWindows()
单张图片测试结果图:
批量裁剪结果:
后续补充和修改:因为cv2默认读取为三通道rgb,如果想保持tiff图的单通道不变,设置第二个参数为-1即可(不懂的可以去查看一下cv2.imread函数的用法以及参数设置详解),并且上面的代码是裁剪大小,下面的resize是插值缩放图片到指定大小,这里是不一样的哟。
image_A = cv2.imread(self.files_A[index % len(self.files_A)], -1)
img_A = cv2.resize(image_A, (256, 256))
img_A = np.reshape(img_A, (256, 256, -1))