在各种比赛、项目的经历中,发现有些代码文件总是用来用去。因此,为了方便自己,也方便大家,将一些自己常用的代码分享一下。
对路径下的所有图片进行改名。
glob
库读取文件os
库改名"""
功能:文件夹下的图片统一改名
"""
import glob
import os
if __name__=="__main__":
path="./*"
path_list=glob.glob(path)
for x in path_list:
#以下部分根据实际情况替换
if x[2]!="C":
temp = x+"/*"
path_ = glob.glob(temp)
for index,i in enumerate(path_):
try:
# print(i)
# print(x+"/"+str(index)+".jpg")
os.rename(i,x+"/"+str(index)+".jpg")
except Exception as e:
print(e)
print('rename file fail\r\n')
else:
# print(i)
# print(path+str(index)+".jpg")
print('rename file success\r\n')
对路径下的所有图片进行尺寸修改。
thread
进行批量修改glob
读取图片cv2
进行图片操作#Antuor:龙文汉
#data:2020.11.20
#Discription:批量修改图像尺寸
import glob
import cv2
import threading
import os
import sys
import time
class Photo_chan:
def __init__(self,dir,save_dir,size):
"""
:param dir: 原路径
:param save_dir: 保存路径
:param size: 图片新尺寸
"""
self.dir = dir
self.save_dir = save_dir
self.photo_list = []
self.name_list = []
self.size = size
self.count = 0
def Resize_image(self,photo_list,save_dir):
"""
:param photo_list: 图片地址的列表
:param save_dir:保存的地址
:return:
"""
# print(photo_list)
for x,i in enumerate(photo_list):
# print(x)
print ("%s: %s" % (name, time.ctime(time.time())))
img = cv2.imread(i)
img = cv2.resize(img,self.size,cv2.INTER_AREA)
#print(save_dir)
if not os.path.isdir(save_dir):
os.mkdir(save_dir)
else:
#print(save_dir + str(x)+".jpg")
cv2.imwrite(save_dir + str(x)+".jpg", img)
def Begin(self,ph):
self.dir = glob.glob(self.dir+"\\*")
thread_list = []
f1 = open("E:\\deeplearning\\pic\\test.txt","w")
for i in self.dir:
x = i.split("\\")[-1]
print(x)
f1.write(str(x)+"\n")
f1.close()
class myThread (threading.Thread):
def __init__(self, threadID, name, photo_list,save_dir,ph):
"""
:param threadID: 线程ID
:param name: 线程名
:param photo_list: 图片名字列表
:param save_dir: 保存路径
:param ph: 自定义的函数
"""
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.photo_list = photo_list
self.save_dir = save_dir
self.ph = ph
def run(self):
print ("开始线程:" + self.name)
self.ph.Resize_image(self.photo_list,self.save_dir,self.name)
print ("退出线程:" + self.name)
if __name__ == "__main__":
ph = Photo_chan("E:\\deeplearning\\pic\\pic",".\\after_image",(320,320))
ph.Begin(ph)
#print(glob.glob(r".\image\jinyinhua\*.jpg"))
根据输入的参数,回值混淆矩阵。
matplotlib
进行绘画。glob
进行文件读取numpy
对矩阵进行操作import matplotlib as plt
import glob
import numpy as np
#confusion_matrix
def Mat(classes_name,confuse,save_name,index=0):
"""
画混淆举证
:param classes_name:输入种类名称作为横纵坐标的值
:param confuse: 混淆矩阵
:param save_name: 保存名
:param index: 当前索引,可忽略
:return:
"""
classes = classes_name
confusion_matrix = np.array(confuse,dtype=np.float64)
plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Oranges) #按照像素显示出矩阵
plt.title(index+'_Confusion_matrix')
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes,rotation=60)
plt.yticks(tick_marks, classes)
thresh = confusion_matrix.max() / 2.
#iters = [[i,j] for i in range(len(classes)) for j in range((classes))]
#ij配对,遍历矩阵迭代器
iters = np.reshape([[[i,j] for j in range(len(confusion_matrix))] for i in range(len(confusion_matrix))],(confusion_matrix.size,2))
# for i, j in iters:
# plt.text(j, i, format(confusion_matrix[i, j])) #显示对应的数字
plt.ylabel('Real label')
plt.xlabel('Prediction')
plt.tight_layout()
#plt.show()
plt.savefig(save_name)
def main(args):
Mat(type_name,confuse,args.confuse_save+"_confuse_mat.jpg",args.confuse_save.split("/")[-1]) #输入种类名和混淆矩阵
根据输入的尺寸比例,讲一张图片切割为多张图片.
cv2
进行图像操作glob
进行文件读取thread
进行批量修改copy
进行复制import cv2
import glob
import threading
import os
import copy
class Cut_photo:
def __init__(self,ori_dir,size=(3,3)):
"""
对图像进行切割
:param ori_dir: 原始路径
:param size: 切割大小,默认切割成新的3*3,共9张图片
"""
self.ori_dir = ori_dir
self.size = size
self.w = self.size[0]
self.h = self.size[1]
self.image_path = glob.glob(self.ori_dir+"/*")
def Cuting(self,single_image_path):
img = cv2.imread(single_image_path)
o_w, o_h, o_c = img.shape
w = int(o_w / self.w)
h = int(o_h / self.h)
c = o_c
after_image = []
for i in range(0, self.w):
temple = copy.deepcopy(img[i * w:(i + 1) * w, :, :])
for x in range(0, self.h):
after_image.append(copy.deepcopy(temple[:, x * h:(x + 1) * h, :]))
for x, i in enumerate(after_image):
save_dir = single_image_path.replace(".jpg", "_" + str(x) + ".jpg")
print(save_dir)
cv2.imwrite(save_dir, i)
def Begin(self):
for i in self.image_path:
print(i)
thread = threading.Thread(target=self.Cuting,args=[i])
thread.start()
thread.join()
if __name__ == "__main__":
test_photo = "1-1.jpg"
for i in range(1,7):
photo_dir = "./type_"+str(i)
my_cut = Cut_photo(photo_dir)
my_cut.Begin()