coco數據集標注圖轉為二值圖python(附代碼)


coco數據集大概有8w張以上的圖片,而且每幅圖都有精確的邊緣mask標注。

后面后分享一個labelme標注的json或xml格式轉二值圖的源碼(以備以后使用)

而我現在在研究顯著性目標檢測,需要的是邊緣mask的二值圖像。搜了很久,並沒有人做過這種工作,只能得到如下的掩膜圖

而我需要的圖像為二值圖,如下

說下 我的過程 並附上代碼:

首先,coco數據集將所有的8w多張圖片標注信息整合到一個json文件中,所以我們需要將單張圖片標注信息json文件提取出來,以下是批量提取腳本。

注: 需要改動地方 1)第6行:將json_file改為原coco數據集json文件的地址 (coco/annotations/xxxxx.json)

                               2)  第13行:設置需要提取的圖片數量 我是提取82000張

                               3)第37行:設置存儲json文件的目錄 需要新建空文件夾 我是放在./coco_single_object下

                               4)第33-35行:可選 將圖片的名稱寫入data.txt中 不需要的話可以注釋掉

 1 # -*- coding:utf-8 -*-
 2 from __future__ import print_function
 3 import json
 4 
 5 #json文件的地址 需要手動設置
 6 json_file='../pycocotools/instances_train2014.json' # # Object Instance 類型的標注
 7 # person_keypoints_val2017.json  # Object Keypoint 類型的標注格式
 8 # captions_val2017.json  # Image Caption的標注格式
 9 
10 data=json.load(open(json_file,'r'))
11 
12 #設置需要提取的圖片數量 我設置提取82000張
13 for i in range(82000):
14     data_2 = {}
15     data_2['info'] = data['info']
16     data_2['licenses'] = data['licenses']
17     data_2['images'] = [data['images'][i]]  # 只提取第一張圖片
18     data_2['categories'] = data['categories']
19     annotation = []
20 
21     # 通過imgID 找到其所有對象
22     imgID = data_2['images'][0]['id']
23     for ann in data['annotations']:
24         if ann['image_id'] == imgID:
25             annotation.append(ann)
26 
27     data_2['annotations'] = annotation
28     # 保存到新的JSON文件,便於查看數據特點
29     #img_file 獲取圖片名稱
30     img_file=data_2['images'][0]['file_name']
31     img_first=img_file.split(".")[0]
32     #將提取出的圖片寫入data.txt文件中並換行 (optional)
33     # with open('./coco_single_object/data.txt',mode='a') as f:
34     #         f.write(img_file)
35     #         f.write("\n")
36     #設置存儲目錄 我的是存在當前目錄下coco_single_object文件夾下 需要手動創建空文件夾
37     json.dump(data_2, open('./coco_single_object/'+img_first+'.json', 'w'), indent=4)  # indent=4 更加美觀顯示

最后的結果是82000張 json文件

---------------------------------------------------------------------------------------------------------------------------------------

有了單張json文件之后,就是將mask掩膜提取出二值圖片的過程了

注:函數傳入4個參數 json_path,img_path,color_img_save,binary_img_save

       分別對應  json_path: 上一步提取出的json文件的文件夾路徑

                       img_path: coco數據集下載時原圖目錄 

                       color_img_save: 存放原圖的目錄 (需要新建此文件夾)

                       binary_img_save: 存放二值圖的目錄(需要新建此文件夾)

 1 from __future__ import print_function
 2 from pycocotools.coco import COCO
 3 import os, sys, zipfile
 4 import urllib.request
 5 import shutil
 6 import numpy as np
 7 import skimage.io as io
 8 import matplotlib.pyplot as plt
 9 import pylab
10 pylab.rcParams['figure.figsize'] = (8.0, 10.0)
11 import os
12 def get_single_binaryImg(json_path,img_path,color_img_save,binary_img_save):
13     # json_path json文件路徑  從coco數據集的annotations標注json文件中提取出的單個json文件
14     #  img_path 原圖目錄   下載coco數據集時的原圖目錄
15     # color_img_save 原圖存放目錄
16     # binary_img_save 二值圖存放目錄
17     dir=os.listdir(json_path)
18     for jfile in dir:
19         annFile =os.path.join(json_path,jfile)
20         coco = COCO(annFile)
21         imgIds = coco.getImgIds()
22         img = coco.loadImgs(imgIds[0])[0]
23         dataDir = img_path
24         shutil.copy(os.path.join(dataDir, img['file_name']), color_img_save)
25 
26         # load and display instance annotations
27         # 加載實例掩膜
28         catIds = []
29         for ann in coco.dataset['annotations']:
30             if ann['image_id'] == imgIds[0]:
31                 catIds.append(ann['category_id'])
32 
33         annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
34         width = img['width']
35         height = img['height']
36         anns = coco.loadAnns(annIds)
37         mask_pic = np.zeros((height, width))
38         for single in anns:
39             mask_single = coco.annToMask(single)
40             mask_pic += mask_single
41 
42         for row in range(height):
43             for col in range(width):
44                 if (mask_pic[row][col] > 0):
45                     mask_pic[row][col] = 255
46 
47         imgs = np.zeros(shape=(height, width, 3), dtype=np.float32)
48         imgs[:, :, 0] = mask_pic[:, :]
49         imgs[:, :, 1] = mask_pic[:, :]
50         imgs[:, :, 2] = mask_pic[:, :]
51         imgs = imgs.astype(int)
52         img_name = img['file_name'].split(".")[0]
53         plt.imsave(binary_img_save + "/" + img_name + ".png", imgs)
54 
55 if __name__ == '__main__':
56 
57     json_path =r"G:\jianfeng\code\dataset\cocoapi-master\PythonAPI\get_json\test"
58     img_path=r"G:\jianfeng\code\dataset\coco\train2014"
59     color_img_save = r"G:\jianfeng\code\dataset\cocoapi-master\PythonAPI\get_json\color_img"
60     binary_img_save = r"G:\jianfeng\code\dataset\cocoapi-master\PythonAPI\get_json\binary_img"
61 
62     get_single_binaryImg(json_path,img_path,color_img_save,binary_img_save)

最終出現這些結果:

     

最后在搜索得到二值圖方法時,也找到了一個不錯的源碼,但是他是將labelme格式的json或者xml轉為二值圖,雖然不是將coco格式轉為二值圖,但是記錄下也許以后也會用的到

https://github.com/samr28/labelme-to-binary-image

 參考:

https://blog.csdn.net/wc781708249/article/details/79603522

https://blog.csdn.net/u013735511/article/details/79099483


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM