yolo标注用cv2画出
import os
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def main(dir_in_dataset,dir_out_label_img):
dir_img = os.path.join(dir_in_dataset, "images")
dir_label = os.path.join(dir_in_dataset, "labels")
path_label_class = os.path.join(dir_label, "classes.txt")
label_classes = []
with open(path_label_class) as f:
class_names = f.readlines()
for class_name in class_names:
label_classes.append(class_name.lower().strip())
files_img_name = os.listdir(dir_img)
for file_img_name in files_img_name:
path_img = os.path.join(dir_img, file_img_name)
split = os.path.splitext(file_img_name)
name = split[0]
path_label = os.path.join(dir_label, name+".txt")
yolo_b_boxes = open(path_label).read().splitlines()
#print("path_img",path_img)
#cv_img = cv2.imread(path_img)
cv_img = cv2.imdecode(np.fromfile(path_img, dtype=np.uint8), -1)
height = cv_img.shape[0]
width = cv_img.shape[1]
for index, b_box in enumerate(yolo_b_boxes):
box = b_box.split(" ")
label_index = int(box[0])
#print(box,width,height)
box_pixel_w = int(float(box[3])*width)
box_pixel_h = int(float(box[4])*height)
box_pixel_x = int(float(box[1])*width) - box_pixel_w // 2
box_pixel_y = int(float(box[2])*height) - box_pixel_h // 2
#print(box_pixel_x,box_pixel_y,box_pixel_w,box_pixel_h)
cv_img = cv2.rectangle(cv_img, (box_pixel_x, box_pixel_y), (box_pixel_x+box_pixel_w, box_pixel_y+box_pixel_h), (0, 0, 255), 1)
#cv2.putText(cv_img, "text",(box_pixel_x,box_pixel_y-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2)
#print("label",label_classes[label_index])
#导入字体文件
fontpath = r'C:\Windows\Fonts\simsun.ttc'
#设置字体的颜色
b,g,r,a = 0,0,255,0
#设置字体大小
font = ImageFont.truetype(fontpath,12)
#将numpy array的图片格式转为PIL的图片格式
img_pil = Image.fromarray(cv_img)
#创建画板
draw = ImageDraw.Draw(img_pil)
#在图片上绘制中文
text = label_classes[label_index]
draw.text((box_pixel_x,box_pixel_y-16),text,font=font,fill=(b,g,r,a))
#将图片转为numpy array的数据格式
cv_img = np.array(img_pil)
dirname = os.path.dirname(path_img)
dirname = dirname.replace('/', '_')
basename = os.path.basename(path_img)
split = os.path.splitext(basename)
img_name = split[0]
#name = dirname + "_" + name + ".jpg"
path_out_img = os.path.join(dir_out_label_img, img_name+".jpg")
print("path_out_img",path_out_img)
#cv2.imwrite(name, cv_img)
cv2.imencode('.jpg',cv_img)[1].tofile(path_out_img)
cv2.namedWindow('label',0)
cv2.imshow('label', cv_img)
cv2.waitKey()
cv2.destroyAllWindows()
main(dir_in_dataset=r"yolo",dir_out_label_img=r"result")
cv2.imwrite(),cv2.imread() 不支持中文路径的处理
cv2.imwrite()
cv2.imwrite(path_name, image)
替换成
cv2.imencode('.jpg',image)[1].tofile(path_name)
cv2.imread()
img = cv2.imread(path_name)
替换成
img=cv2.imdecode(np.fromfile(path_name,dtype=np.uint8),-1)