日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python用opencv將標注提取畫框到對應的圖像中_python

作者:徽先生 ? 更新時間: 2022-10-19 編程語言

前言

問題需求:

擁有兩個文件夾,一個保存圖片image,一個保存標簽文件,要求把標簽文件中的標注提取出來,并在圖片中畫出來

相應的思路

  • 首先提出各個文件的路徑;
  • 然后將解析json文件,將其中的標注文件提取,并將對應的圖像讀取在圖像上將對應的框畫出來;由于圖像以及標簽的文件前綴都是一樣的,所以只要一個前綴列表提取出來,然后將圖像的路徑與其進行拼接(圖像路徑+前綴+.jpeg)就可以讀取對應的圖像,而寫入的圖像也是一樣(寫入圖像路徑+前綴+.jpeg),標簽文件也是一樣(標簽路徑+前綴+.json)

讀取前綴列表

  • 通過os.walk()迭代讀取文件夾以及相應的文件列表
  • 通過os.listdir直接讀取文件夾下的文件列表
# 通過os.walk()讀取文件夾以及相應的文件列表
def get_file_list(path):
    file_list=[]
    for dir_list,folder,file in os.walk(path):
        file_list=file
    return file_list

#通過os.listdir()讀取文件夾下的文件列表
def get_file_list2(path):
    file_list=os.listdir(path)
    return file_list
file_list=get_file_list2(r"E:\temp\AI\label")
print(file_list)

找出json結構中對應框坐標位置,畫出對應的框

查看json文件結構,對應找到坐標所在的位置:

  • 可以看到json文件中坐標是在shapes對應的points里的列表,而且是列表第0項表示左上位置,而第一項表示右上位置,所以在cv2的畫框的兩個參數參數pt1和pt2就定下來cv2.rectangle(img, pt1, pt2, color, thickness=None )
{
  "version": "3.16.5",
  "flags": {},
  "shapes": [
    {
      "label": "0",
      "line_color": null,
      "fill_color": null,
      "points": [
        [
          2720.0,
          1094.0
        ],
        [
          2768.0,
          1158.0
        ]
      ],
      "shape_type": "rectangle",
      "flags": {}
    }
  ],
...
}

那么代碼就如下所示:

import json
import cv2
path_label=r"E:\temp\AI\label"
path_img=r"E:\temp\AI\image"
path_result=r"E:\temp\AI\result"
# 通過遍歷將圖像紛紛畫框
for file in file_list:
    txt=open(os.path.join(path_label,file))
    load_json=json.load(txt)
    for shape in load_json["shapes"]:
        left_top=(int(shape["points"][0][0]),int(shape["points"][0][1]))
        right_bottom=(int(shape["points"][1][0]),int(shape["points"][1][1]))
        #對象進行畫框
        img_name=file.split(".")[0]+".jpeg"
        img=cv2.imread(os.path.join(os.path.join(path_img,img_name)))
        cv2.rectangle(img, left_top,right_bottom, (0, 255, 0), 2)
        cv2.imwrite(os.path.join(path_result,img_name), img)

比如其中一個圖像的一個缺陷位置就被標注出來

原文鏈接:https://blog.csdn.net/weixin_42295969/article/details/126414920

欄目分類
最近更新