在做语义分割时,复现GitHub代码,出现了语义类标签随机的问题,最终定位到是转换为调试盘时没有统一调色盘,为了节省时间,将代码写为多进程,现将完整代码分享。
from PIL import Image, ImageDraw, ImageFont
import os
import cv2
import numpy as np
import multiprocessing
def get_all_colorsjr(infile):#获取主要颜色
colors_set = set()
names = os.listdir(infile)
for name in names:
if not (name.endswith('jpg') or name.endswith('png')):
print('errname',name)
continue
lab_name = os.path.join(infile,name)
image = Image.open(lab_name)
# print(image.mode)
# small_image = image.resize((10, 10))
small_image = image
width = small_image.size[0]
height = small_image.size[1]
for i in range(0, width):
for j in range(0, height):
a = small_image.getpixel((i, j))
colors_set.add(a)
colors_set_list = list(colors_set)
colors_set_list.sort()
colors_dict = {}
for colors in colors_set_list:
colors_dict[colors] = colors_set_list.index(colors)
print('colors_dict',colors_dict)
return colors_dict
def OsDistance(vector1, vector2): # 计算欧式距离
n1 = float(vector1[0])
n2 = float(vector1[1])
n3 = float(vector1[2])
m1 = float(vector2[0])
m2 = float(vector2[1])
m3 = float(vector2[2])
distance = ((n1 - m1) ** 2 + (n2 - m2) ** 2 + (n3 - m3) ** 2) ** 0.5
return distance
def calculate_distance( a,c): #找到最相近的颜色,并取出标签
m=[]
for ci in c:
d=OsDistance(a,ci)
m.append(d)
t=m.index(min(m))
return t
def RGB2P(img_name,palette,colors):
img = Image.open(img_name)
# cv_img = cv2.imread(img_name)
if img.mode !='P':
print('61img_name',img_name,img.mode)
# img = Image.open(img_name)
width = img.size[0]
height = img.size[1]
temp = 1
# img = img.convert("P", palette=Image.ADAPTIVE)
imgP = img.convert("P")
imgP.putpalette(palette)
for i in range(0, width):
for j in range(0, height):
a=img.getpixel((i,j))
try:
b=calculate_distance(a,colors)
# b = colors.index(a)
imgP.putpixel((i, j), colors[b])
except Exception as e:
print('errimg_name',img_name,e)
raise a
# imgP = img.convert("P")
# img = img.convert("P",palette=Image.ADAPTIVE)
# img.palette.colors = colors_dict
# img.putpalette(palette)
# imgP.save(img_name[:-4]+'_PP.png')
imgP.save(img_name)
# print('ok')
# imgPP = Image.open(img_name[:-4]+'_PP.png')
# print(imgP.palette.colors)
else:
print('81', img_name,img.mode)
# raise img_name
if __name__ == '__main__':
colors = [(0, 0, 0), (85, 255, 0), (53, 119, 181), (255, 0, 255), (245, 128, 6), (255, 255, 127), (255, 0, 0),(255, 255, 255)]
# colors_dict = {(0, 0, 0):0,(85, 255, 0):1,(53, 119, 181):2,(255, 0, 255 ):3,(245, 128, 6 ):4,(255, 255, 127):5,(255, 0, 0 ):6,(255, 255, 255):7}
palette = []
for i in range(8):
palette.extend((i, i, i))
# 原来的,图片颜色有问题,绿色和红色反的
palette[:3 * 8] = np.array([(0, 0, 0), (85, 255, 0), (53, 119, 181), (255, 0, 255), (245, 128, 6), (255, 255, 127), (255, 0, 0),(255, 255, 255)], dtype='uint8').flatten()
# # 翻转之后,列表标签超出,无法编码,不能用
# palette[:3 * 8] = np.array(
# [(0, 0, 0), (0, 255, 85), (181, 119, 53,), (255, 0, 255), (6, 128, 245), (127, 255, 255), (0, 0, 255),(255, 255, 255)], dtype='uint8').flatten()
path_my = r''
# get_all_colorsjr(path_my)
pool = multiprocessing.Pool(processes=20)
for img_name in os.listdir(path_my):
img_name = os.path.join(path_my, img_name)
# print('img_name',img_name)
pool.apply_async(func=RGB2P, args=(img_name,palette,colors))
pool.close()
pool.join() # 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
print('gg')
通过下面代码打印的set_P 判断生成的调色盘有没有问题,即判断生成的类有几种,每个类分别对应什么颜色。
from PIL import Image
import os,cv2
import multiprocessing
dict = {}
set_P = set()
count = 0
def Check(img_name):
global dict
global set_P
global count
print('img_name', img_name)
img = Image.open(img_name)
cv_img = cv2.imread(img_name)
# # print(cv_img.shape[2])
# if cv_img.shape[2]!=3:
# print(cv_img.shape)
if img.mode !='P':
print('23img.mode !=P',img_name,img.mode)
# continue
# # img = img.convert('P')
# img = img.convert("P", palette=Image.ADAPTIVE)
# # img.save(img_name)
# print(img.mode)
elif img.mode =='P':
# print(img.size)
print('31img.palette.colors',img.palette.colors)
for x in range(img.size[0]):
for y in range(img.size[1]):
if img.getpixel((x,y)) !=1 or True:
# print(img.getpixel((x,y)))
# print(cv_img[y][x])
dict[str(cv_img[y][x])] = img.getpixel((x,y))
set_P.add(str(img.getpixel((x,y)))+"______"+str(cv_img[y][x]))
print('dict',count,len(dict),dict)
print('set_P',count,len(set_P),set_P)
count+=1
# break
from mv_similar import simJr
if __name__ == '__main__':
path_my = r''
# path_my = path_ori
for img_name in os.listdir(path_my):
img_name = os.path.join(path_my, img_name)
pool = multiprocessing.Pool(processes=30)
for img_name in os.listdir(path_my):
img_name = os.path.join(path_my, img_name)
# print('img_name',img_name)
pool.apply_async(func=Check, args=(img_name,))
# pool.apply_async(func=simJr, args=('img_name','s'))
pool.close()
pool.join() # 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束