首頁 > 軟體

yolov5返回座標的方法範例

2022-03-17 13:00:29

yolov5返回座標(v6版)

1 、從yolov5資料夾李找到detect.py,按Ctrl+F 輸入annotator.box_label;

if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))

2、找到這個程式碼後按住ctrl鍵,滑鼠點選box_label,就會跳到plots.py檔案並定位到box_label定義的地方;

3、找到p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])),在這行程式碼下面新增:

print("左上點的座標為:(" + str(p1[0]) + "," + str(p1[1]) + "),右下點的座標為(" + str(p2[0]) + "," + str(p2[1]) + ")")

4、完成後的程式碼如下:

def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
        # Add one xyxy box to image with label
        if self.pil or not is_ascii(label):
            self.draw.rectangle(box, width=self.lw, outline=color)  # box
            if label:
                w, h = self.font.getsize(label)  # text width, height
                outside = box[1] - h >= 0  # label fits outside box
                self.draw.rectangle([box[0],
                                     box[1] - h if outside else box[1],
                                     box[0] + w + 1,
                                     box[1] + 1 if outside else box[1] + h + 1], fill=color)
                # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')  # for PIL>8.0
                self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)
        else:  # cv2
            p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
            print("左上點的座標為:(" + str(p1[0]) + "," + str(p1[1]) + "),右下點的座標為(" + str(p2[0]) + "," + str(p2[1]) + ")")
            
            cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)

5、測試情況:回到命令列,cd到yolov5資料夾,輸入指令:python detect.py --source ../mask.1.jpg,其中mask.1.jpg應改為你yolov5資料夾下的圖片名稱;按確認鍵後執行就發現輸出的資訊多了剛才新增的一行

(venv) (base) rongxiao@rongxiao:~/PycharmProjects/yolococo/yolov5$ python detect.py --source ../mask.1.jpg
detect: weights=yolov5s.pt, source=../mask.1.jpg, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False
YOLOv5 

IT145.com E-mail:sddin#qq.com