최근에 의미론적 분할 프로젝트를 진행하고 있었는데 Label 도구를 이용하여 카테고리를 표시했더니 카테고리마다 색상이 다르게 나오더라구요 코드가 필요하시면 참고하시면 됩니다 나중에 하나의 카테고리가 포함된 사진 과 카테고리가 포함된 사진을 세고 싶어요 전체 그림의 비율로 다음은 내 코드입니다:
코드 아이디어:
1) 폴더의 그림을 주기적으로 읽기
2) 그림의 픽셀이 픽셀과 일치할 때 그림의 각 픽셀을 주기적으로 읽습니다. 감지한 물체의 해당 범주에 1을 더합니다
3) 그림을 읽은 후 각 범주의 비율을 계산합니다.
import cv2
import os
import matplotlib.pyplot as plt
picture_path="/home/wsb/桌面/picture"
picture_list=os.listdir(picture_path)
total_picture=len(picture_list)
total=total_picture
per=[]
number=0#图片中道路类型为1的个数
number1=0#一种道路类型并且比例小于0.0638的个数
number2=0
for item in picture_list:
src = os.path.join(os.path.abspath(picture_path), item)
print("start: %s "%item)
total_picture-=1
mat=cv2.imread(src)
height=mat.shape[0]
width=mat.shape[1]
ground=0
zero=0
one=0
two=0
three=0
four=0
five=0
six=0
seven=0
eight=0
rateground=0
rate0=0
rate1=0
rate2=0
rate3=0
rate4=0
rate5=0
rate6=0
rate7=0
rate8=0
rate=0
road_type=0
for i in range(height):
for j in range(width):
# print("r:%s"%mat[i][j][0])
# print("r:%s"%mat[i][j][1])
# print("r:%s"%mat[i][j][2])
'''
我这里共有9种分类情况,况且我已知道每一种颜色的具体rgb值,我将它们作为我的判断条件
如不你不知道可以在网上查找自己想查看比例的rgb值或者范围
'''
if mat[i][j][0]==0 and mat[i][j][1]==0 and mat[i][j][2]==0:
ground+=1
elif mat[i][j][0]==128 and mat[i][j][1]==0 and mat[i][j][2]==0:
zero+=1
elif mat[i][j][0]==0 and mat[i][j][1]==128 and mat[i][j][2]==0:
one+=1
elif mat[i][j][0]==128 and mat[i][j][1]==128 and mat[i][j][2]==0:
two+=1
elif mat[i][j][0]==0 and mat[i][j][1]==0 and mat[i][j][2]==128:
three+=1
elif mat[i][j][0]==128 and mat[i][j][1]==0 and mat[i][j][2]==128:
four+=1
elif mat[i][j][0]==0 and mat[i][j][1]==128 and mat[i][j][2]==128:
five+=1
elif mat[i][j][0]==128 and mat[i][j][1]==128 and mat[i][j][2]==128:
six+=1
elif mat[i][j][0]==0 and mat[i][j][1]==0 and mat[i][j][2]==64:
seven+=1
elif mat[i][j][0]==0 and mat[i][j][1]==0 and mat[i][j][2]==192:
eight+=1
else:
print("输入正确的图片,或者更改上面判断条件的像素值")
rateground=ground/(height*width)
rate0=zero/(height*width)
if rate0!=0:
road_type+=1
rate1=one/(height*width)
if rate1!=0:
road_type+=1
rate2=two/(height*width)
if rate2!=0:
road_type+=1
rate3=three/(height*width)
if rate3!=0:
road_type+=1
rate4=four/(height*width)
if rate4!=0:
road_type+=1
rate5=five/(height*width)
if rate5!=0:
road_type+=1
rate6=six/(height*width)
if rate6!=0:
road_type+=1
rate7=seven/(height*width)
if rate7!=0:
road_type+=1
rate8=eight/(height*width)
if rate8!=0:
road_type+=1
rate=rate0+rate1+rate2+rate3+rate4+rate5+rate6+rate7+rate8
per.append(rate)
if road_type==1:
number+=1
if rate<0.0638:
number1+=1#一种类型道路并且所占比例小于0.0638的情况
else:
if rate<0.532:
number2+=1#两种道路类型,并且正确正确道路类型所占比例小于0.532时的个数
print("the remaining %d"%total_picture)
A=number/total#图片中道路类型大于1种的概率
A1=number1/total#图片中一种道路类型并且比例小于0.0638的概率
A2=number2/total#图片中有两种道路,并且一种道路所占比例小于0.532时的概率
print("A1:%s"%A1)
print("the precentage of one road is %s"%A)
print("the precentage of two road is %s"%(1-A))
print("A2:%s"%A2)
plt.plot(per)
plt.ylabel('the percentage of road')
plt.show()