ncolors(num)主要用來生成num個區分度較大的RGB顏色值,參考如下:
鏈接
import cv2 as cv
import os
import colorsys
import random
def get_n_hls_colors(num):
hls_colors = []
i = 0
step = 360.0 / num
while i < 360:
h = i
s = 90 + random.random() * 10
l = 50 + random.random() * 10
_hlsc = [h / 360.0, l / 100.0, s / 100.0]
hls_colors.append(_hlsc)
i += step
return hls_colors
def ncolors(num):
rgb_colors = []
if num < 1:
return rgb_colors
hls_colors = get_n_hls_colors(num)
for hlsc in hls_colors:
_r, _g, _b = colorsys.hls_to_rgb(hlsc[0], hlsc[1], hlsc[2])
r, g, b = [int(x * 255.0) for x in (_r, _g, _b)]
rgb_colors.append([r, g, b])
return rgb_colors
def convert(bbox,shape):
x1 = int((bbox[0] - bbox[2] / 2.0) * shape[1])
y1 = int((bbox[1] - bbox[3] / 2.0) * shape[0])
x2 = int((bbox[0] + bbox[2] / 2.0) * shape[1])
y2 = int((bbox[1] + bbox[3] / 2.0) * shape[0])
return (x1,y1,x2,y2)
n = 6 # 類別數
# 獲取n種區分度較大的rgb值
colors = ncolors(n)
images_list = os.listdir('images') # 獲取圖片名串列
images_dir = 'images/' # 圖片目錄
labels_dir = 'labels/' # label目錄
output_dir = 'output/' # 輸出圖片目錄
for img_id in images_list:
img = cv.imread(images_dir + img_id)
# 判斷后綴是為了排除隱藏檔案.ipynb_checkpoints
if img_id[-3:] != 'jpg':
continue
shape = img.shape[0:2]
txt_id = img_id.replace('jpg', 'txt')
with open(labels_dir + txt_id) as r:
lines = r.readlines()
for line in lines:
line = [float(i) for i in line.split(' ')] # 按空格劃分并轉換float型別
label = int(line[0]) #獲取類別資訊
bbox = line[1:] # 獲取box資訊
(x1,y1,x2,y2) = convert(bbox,shape)
cv.rectangle(img, (x1, y1), (x2, y2), (colors[label][2], colors[label][1], colors[label][0]), 3)
cv.waitKey(0)
cv.imwrite(output_dir + img_id,img)
注意:OpenCV對RGB影像資料的存盤順序是BGR,rectangle函式中Scalar的順序也是B,G,R,
如Scalar( 0, 0, 255)代表的是紅色,
效果圖
![]() | ![]() |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/345578.html
標籤:其他
上一篇:PaddleOCR的服務部署


