使用opencv-python修改图片格式和尺寸

对于遥感图像的小patch, 在不改变分辨率的情况下将patch尺寸扩大到特定尺寸. 读取文件夹内所有特定后缀文件并拷贝到另一个文件夹内.
参考代码:
用Python复制文件的9个方法
用python实现tif图片批量转化成jpg格式图片
机器学习进阶-图像基本操作-边界补全操作

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 24 08:22:58 2020@author: deyiwang@qq.com
"""import datetime
import io, os
from PIL import Image
import shutil
import cv2
import numpy as np
import matplotlib.pyplot as plt inputPathRoot = 'E:\\opensartotal_cifar10\\'#'C:\\Users\\奥利给\Desktop\\sentinel_sar_ship\\sentinel_sar_ship\\'
outputPathRoot = 'E:\\opensartotal_cifar10\\13'
# 如果目标目录还不存在,则进行创建
if not os.path.exists(outputPathRoot):os.mkdir(outputPathRoot)  # 创建目录#------------------------step I 拷贝文件-----------------------------------#
flag_transform = 0
# 搜索数据中特定格式的文件, 拷贝到另一个文件夹内
if flag_transform:if 1:print(str(datetime.datetime.now()) + " 开始转换 ......... ")counter = 0for roots, dirs, files in os.walk(inputPathRoot):for index in range(len(files)):formatFile = files[index].split('.')[-1]if formatFile == 'tif':#        print(files)#        for name in files:#            if '.JPG' in name:#                print(name)oldFilePath = os.path.join(roots, files[index])if 'Patch_Uint8' in oldFilePath:newroots = roots.replace(inputPathRoot,outputPathRoot)if not os.path.exists(newroots):os.makedirs(newroots)newFilePath = os.path.join(outputPathRoot, files[index])shutil.copyfile(oldFilePath, newFilePath)#            os.system("mstar2jpeg -i %s -o %s -q 95" % (oldFilePath,newFilePath))counter += 1print('已经转换 %s 张图' % (counter))print(str(datetime.datetime.now()) + " 完成 ! ! !  ")else :print('转换功能未激活')   #------------------------step II 图片转换-----------------------------------#
flag_change_format = 0
# 读取图像, 转换格式, 裁剪, 加黑边(保持分辨率)
if flag_change_format:print(str(datetime.datetime.now()) + " 图片格式转换功能激活 ")counter = 0classes = []for roots, dirs, files in os.walk(inputPathRoot):for index in range(len(files)):formatFile = files[index].split('.')[-1]name = files[index].split('_')[1].replace(' ','')if name not in classes:classes.append(name)
#            print(name)if formatFile == 'tif':oldFilePath = os.path.join(roots, files[index])
#                print(oldFilePath)img = cv2.imread(oldFilePath)newroots = roots.replace(inputPathRoot,outputPathRoot)if not os.path.exists(newroots):os.makedirs(newroots)name = name + '_' + str(counter).zfill(5)newFilePath = os.path.join(newroots, name)newFilePath = str(newFilePath) + '.jpg'
#                print(newFilePath)h, w, c = img.shapeif h<=128 and w<=128:
#cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_CONSTANT, value=0)img = cv2.copyMakeBorder(img,64-h//2, 64-h//2, 64-w//2, 64-w//2,cv2.BORDER_CONSTANT, value=0)img2 = cv2.resize(img, (128, 128), interpolation=cv2.INTER_CUBIC)elif h>128 and w<=128:img = cv2.copyMakeBorder(img,h,128,0,0,cv2.BORDER_CONSTANT,value=0)img2 = crop_image(img, 128)elif h<=128 and w>128:img = cv2.copyMakeBorder(img, 128, w,0,0,cv2.BORDER_CONSTANT,value=0)img2 = crop_image(img, 128)else:img2 = crop_image(img, 128)cv2.imwrite(newFilePath, img2)counter += 1print('已经转换 %s 张图' % (counter))print(str(datetime.datetime.now()) + " 完成 ! ! !  ")print(f'一共有{len(classes)}类别',classes)#------------------------step III 将图片整理成CIFAR10文件格式-----------------------------------#
flag_copy_reorganize = 0
if flag_copy_reorganize:# 将图片整理成cifar10格式, 各个类别分别保存到自己类别的文件夹内print(str(datetime.datetime.now()) + " CIFAR10文件整理功能激活 ")counter = 0for roots, dirs, files in os.walk(inputPathRoot):for index in range(len(files)):name = files[index].split('_')[0]oldFilePath = os.path.join(roots, files[index])img = cv2.imread(oldFilePath)newroots = roots.replace(inputPathRoot,outputPathRoot)if not os.path.exists(newroots):os.makedirs(newroots)newFilePath = os.path.join(newroots, name, files[index])newFilePath_ = os.path.join(newroots, name)if not os.path.exists(newFilePath_):os.makedirs(newFilePath_)
#            print(newFilePath)cv2.imwrite(newFilePath, img)  print(str(datetime.datetime.now()) + " CIFAR10文件整理完毕 ")#------------------------step IV 重命名-----------------------------------#
def rename_pics(path):filelist = os.listdir(path)count=0
#    for file in filelist:
#        print(file)for file in filelist:   Olddir=os.path.join(path,file)  if os.path.isdir(Olddir):  continuefilename=os.path.splitext(file)[0]   filetype=os.path.splitext(file)[1]  Newdir=os.path.join(path,outputPathRoot.split('\\')[-1]+'_'+str(count).zfill(5)+filetype)  os.rename(Olddir,Newdir)count+=1
#        print(Newdir)flag_rename = 0
if flag_rename:rename_pics(outputPathRoot)def crop_image(image, size):   # image_dir 批量处理图像文件夹 size 裁剪后的尺寸h, w = image.shape[0:2]h_no = h // sizew_no = w // sizefor row in range(0, h_no):for col in range(0, w_no):cropped_img = image[size*row : size*(row+1), size*col : size*(col+1), : ]return cropped_img#------------------------step V 检验数量-----------------------------------#
flag_count = 0
# 搜索数据中特定格式的文件, 拷贝到另一个文件夹内
if flag_count:if 1:print(str(datetime.datetime.now()) + " counting ......... ")counter = 0for roots, dirs, files in os.walk(inputPathRoot):for index in range(len(files)):formatFile = files[index].split('.')[-1]if formatFile == 'jpg':counter += 1print('total %s 张图' % (counter))  

对中文路径下的图片进行切分,并且按照总的图片数量标记名称


# -*- coding: utf-8 -*-  import cv2
import os
from osgeo import gdal 
import numpy as npCOUNT = 0def modi_count():global COUNTCOUNT += 1return COUNTdef create_folder(path):if not os.path.exists(path):os.mkdir(path)def slid_win(imgpp, out_folder, win = 256, step_num = 1):create_folder(out_folder)height, width, _ = imgpp.shape# print(imgpp.shape)height = height//win*win + winwidth = width//win*win + winimgpp = cv2.resize(imgpp,(width,height))# print(imgpp.shape,height/win,width/win)# cv2.imshow('',imgpp)step = win//step_numstart_x = 0#width//2start_y = 0#height//2end_x = width#*3//4end_y = height#*2//3new_img_big = imgpp[start_y:end_y,start_x:end_x]new_path = os.path.join(out_folder,'trimmed_big.jpg')cv2.imencode('.jpg',new_img_big)[1].tofile(new_path)# cv2.imwrite(new_path,new_img_big)y, x = start_y,start_xwhile y+win <= end_y:x = start_xwhile x+win <= end_x:x += stepif y+win<= height and x+win<=width:count = modi_count()new_img = imgpp[y:y+win,x:x+win]new_name = str(count).zfill(5)+'.jpg'new_path = os.path.join(out_folder,new_name)# cv2.imwrite(new_path,new_img)cv2.imencode('.jpg',new_img)[1].tofile(new_path)y += stepprint('left:',height-y,width-x,'total:',count)if __name__=='__main__':dir_name = ['001', '002', '003', '004']for i in dir_name:path = inameList = os.listdir(path)for i in range(len(nameList)):img_path = os.path.join(path,nameList[i])print(img_path)img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), 1)#cv2.imread(img_path)# print('img'+str(i))create_folder('new_' + path)new_folder = 'new_'+ str(os.path.join(path,nameList[i]))[:-4]# print(new_folder)# breakslid_win(img, win = 256, step_num = 1, out_folder=new_folder)


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部