python图片预处理基本操作之——批量重命名,修改格式,统一大小
import os
from PIL import Image
import glob
import cv2 as cv
class bathrename():
def __init__(self):
self.path = "D:/Users/clg2021/Desktop/data4"#文件夹的地址
self.value=0 #初始变量为0
def rename_resize(self, label):#归一化文件夹中的其中一个文件的图片
isExist = os.path.exists(self.path)
if isExist:
for file in os.listdir(self.path):
if file == label:
path1 = self.path + str('/' + label)
for name in os.listdir(path1):
bathrename.rename(self, name, path1)
else:
print("地址不正确!")
def rename(self, file, path):#重新命名文件名
if file.endswith('.bmp'):
src = os.path.join(os.path.abspath(path), file)
dst = os.path.join(os.path.abspath(path), 'july' + str(self.value) + '.jpg')
try:
os.rename(src, dst)
#print('converting %s to %s ...' % (src, dst))
self.value= self.value + 2
except:
print('bmp_error')
elif file.endswith('.jpg'):
src = os.path.join(os.path.abspath(path), file)
dst = os.path.join(os.path.abspath(path), 'judk' + str(self.value) + '.jpg')
try:
os.rename(src, dst)
bathrename.re_size(self,dst)
#print('convert %s to %s ...' % (src, dst))
self.value = self.value + 1
except:
print('jpg_error')
def re_size(self, jpgfile, width=32, height=64):#归一化图片尺寸,并进行二值化处理
image = cv.imread(jpgfile)
gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray_image, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
try:
new_image = cv.resize(binary, (width, height), cv.INTER_CUBIC)
print(jpgfile)
cv.imwrite(jpgfile, new_image)
except Exception as e:
print(e)
def test_image(self, image_path):
image = cv.imread(image_path)
gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray_image, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
cv.imshow("image", image)
cv.imshow("binary", binary)
cv.waitKey()
cv.destroyAllWindows()
if __name__ == '__main__':
demo = bathrename()
labe = 'Z'
demo.rename_resize(labe)