【8】python實現根據EXCEL表格的分類索引完成圖片的分類

【1】背景:如圖所示,左邊爲圖片的索引(默認爲第一列),右邊爲圖片名(默認爲第二列)。根據左邊的類別完成對右邊圖片的分類。

【2】代碼

# -*- coding: utf-8 -*-
"""
author:songjian"""

import xlrd
import cv2
import os

#讀取數據存入字典
def read_excel(name):
	#打開excel表,填寫路徑
	book = xlrd.open_workbook(name)
	#找到sheet頁
	table = book.sheet_by_name(sheetname)
	row_Num = table.nrows
	col_Num = table.ncols
	s =[]
	key=table.col_values(1)
	values=table.col_values(0)
	print(key)
	print(values)
	#print(key)
	if row_Num <= 1:
		print("沒數據")
	else:
		for i in range(row_Num):
			d ={}
			# 把key值對應的value賦值給key,每行循環
			d[round(int(key[i]))]=round(int(values[i]))
			# 把字典加到列表中
			s.append(d)
		return s


#讀入圖片進行分類
def read__image(open_path,index_name,sheetname,save_path):
	nums=0
	images=[]
	#文件分類索引。鍵爲待處理的圖片名,值爲被劃分的類別數
	picindex=read_excel(index_name)
	#print(picindex)
	for dir_image in os.listdir(open_path): # os.listdir() 方法用於返回指定的文件夾包含的文件或文件夾的名字的列表
		full_path = os.path.abspath(os.path.join(open_path,dir_image))
		#圖片的類別分爲123
		class_image=0
		if dir_image.endswith('.bmp'):
			image = cv2.imread(full_path)
			#判斷圖片的類別
			#分離文件路徑和文件名
			(filepath, filename) = os.path.split(full_path)
			#分離文件名和後綴,[0]表示選擇文件名,[1]表示選擇後綴
			imagename = os.path.splitext(filename)[0]
			for list_index in range(len(picindex)):
				for key, value in picindex[list_index].items():
					if str(key)==str(imagename):
						class_image=value
						print(class_image)
			#粒細胞
			sheet_image=str(sheetname)+str(imagename)
			if class_image==1:
				image_path = save_path[class_image-1]+'%s-%s.jpg' % ('Neu',sheet_image)
				print(image_path)
				cv2.imwrite(image_path, image)
				#print("save successful")
			#淋巴細胞
			elif class_image==2:
				image_path = save_path[class_image-1]+'%s-%s.jpg' % ('Lym',sheet_image)
				cv2.imwrite(image_path, image)
				#print("save successful")
			#其他細胞
			elif class_image==3:
				image_path = save_path[class_image-1]+'%s-%s.jpg' % ('Other',sheet_image)
				cv2.imwrite(image_path, image)
				#print("save successful")
			else:
				#print("this image need to be delete")
				print("delete successful")
			nums=nums+1
	info="nums:"+str(nums)
	print(info)

if __name__ == '__main__':
	#圖片打開路徑
	open_path="D:\\pythonprocedure\\classimage\\4820\\"
	#excel表格路徑
	name="4820.xls"
	#excel表名
	sheetname="4820"
	#三個文件夾路徑123
	save_path=[]
	path1="D:\\pythonprocedure\\classimage\\train\\"
	path2="D:\\pythonprocedure\\classimage\\train\\"
	path3="D:\\pythonprocedure\\classimage\\train\\"
	save_path.append(path1)
	save_path.append(path2)
	save_path.append(path3)
	read__image(open_path,name,sheetname,save_path)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章