import cv2
import os
import sys
from PIL import Image
# def edge(filepath,destpath):
# PathDir = os.listdir(filepath)
# for allDir in PathDir:
# print(allDir)
# child = os.path.join(filepath,allDir)
# dest = os.path.join(destpath,allDir)
# if not os.path.exists(destpath):
# os.makedirs(destpath)
#
# if os.path.isfile(child):
# img = cv2.imread(child)
# if child is None:
# print('Faile')
# sys.exit()
#
#
# #dat = cv2.flip(img,0)
# retal , dst =cv2.threshold(dat,0,255,cv2.THRESH_BINARY)
# cv2.imwrite(dest,dst)
# def rename(picpathlist):
# for i in range(0,len(picpathlist)):
# pic_rename = picpathlist[i].rsplit("\\",1)[0]
# os.rename(picpathlist[i],pic_rename + "\\" + str(int(i)+1) + ".jpg")
# print(pic_rename + "\\" + str(int(i)+1) + ".jpg")
def cut(filepath,destpath): #重采样
pathDir = os.listdir(filepath)
for allDir in pathDir:
print(allDir)
child = os.path.join(filepath, allDir)
dest = os.path.join(destpath,allDir)
if os.path.isfile(child):
img = cv2.imread(child)
if child is None:
print('faile')
sys.exit()
w = 384
h = 384
img1 = cv2.resize(img,(w,h),interpolation=cv2.INTER_NEAREST) #最近邻
cv2.imwrite(dest,img1)
def interpolation(destpath): #边界填充
pathDir = os.listdir(destpath)
for allDir in pathDir:
print(allDir)
#child = os.path.join(filepath,allDir)
dest = os.path.join(destpath,allDir)
if os.path.isfile(dest):
img = cv2.imread(dest)
if dest is None:
print('faile')
sys.exit()
top_size, bottom_size, left_size, right_size = [64,64,64,64]
#edge1 = cv2.copyMakeBorder(img,top_size, bottom_size, left_size, right_size,cv2.BORDER_CONSTANT, value=0)
reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,
borderType=cv2.BORDER_REFLECT_101)
cv2.imwrite(dest,reflect101)
def image_binarization(destpath):
pathDir = os.listdir(filepath)
for allDir in pathDir:
dest = os.path.join(destpath,allDir)
if os.path.isfile(dest):
image = cv2.imread(dest)
print(dest)
n,s = os.path.splitext(dest)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
retval, dst = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) #dst二值化图像
cv2.imwrite(dest,dst)
if __name__ == "__main__":
filepath = r'E:\1\yuan'
destpath = r'E:\1\yuan512'
cut(filepath,destpath)
interpolation(destpath)
image_binarization(destpath)
批量重采样、边界填充、二值化
于 2022-10-18 15:23:32 首次发布