labelme标注的图片转png
unet自带的json_to_dataset.py有点问题。用这个转比较好
点击查看代码
import random
import cv2 as cv
import json
import numpy as np
from matplotlib import pyplot as plt
from skimage.draw import draw
import os
import math
# from argmentation import rotate_image, perspective_tranform
class Process:
def __init__(self):
self.path = ""
self.imgs_path = []
self.save_path = ""
self.JZW_COUNT = [0,0,0,0,0,0,0,0,0]
self.img_COUNT = [0, 0, 0, 0, 0, 0, 0, 0, 0]
def loadjson(self, path, savepath):
self.path = path
self.imgs_path = os.listdir(path)
self.save_path = savepath
def run(self, cropType):
for imgpath in self.imgs_path:
if imgpath.endswith('jpg'):
mask = self.json2voc(imgpath)
img = cv.imread(self.path + imgpath)
self.enhance(img, mask, imgpath)
# print(imgpath + "----Enhance")
# print("----------------------")
# self.crop(cropType)
# img_voc = cv.resize(img_voc, (int(img_voc.shape[1] / 2), int(img_voc.shape[0] / 2)))
# cv.imshow('255', img_voc)
# cv.waitKey(0)
def json2voc(self, imgpath):
img = cv.imread(self.path + imgpath)
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
mask = np.zeros(img.shape, np.uint8)
mask = mask
jzw_flag = [0,0,0,0,0,0,0,0,0]
with open(self.path + imgpath[:-3] + 'json', encoding='utf-8') as a:
# 读取文件
result = json.load(a)
# 获取姓名
shapes = result.get('shapes')
for i in shapes:
crack = i['points']
X = []
Y = []
for j in range(len(crack)):
crack[j][0] = int(crack[j][0])
crack[j][1] = int(crack[j][1])
X.append(crack[j][1])
Y.append(crack[j][0])
rr, cc = draw.polygon(np.array(X), np.array(Y))
if i['label'] == 'jing':
draw.set_color(mask, [rr, cc], [1])
self.JZW_COUNT[0] += 1
jzw_flag[0] = 1
elif i['label'] == 'B':
draw.set_color(mask, [rr, cc], [2])
self.JZW_COUNT[1] += 1
jzw_flag[1] = 1
elif i['label'] == 'C':
draw.set_color(mask, [rr, cc], [3])
self.JZW_COUNT[2] += 1
jzw_flag[2] = 1
elif i['label'] == 'D':
if i['shape_type'] == 'circle':
circle_data = i['points']
center = (int(circle_data[0][0]), int(circle_data[0][1]))
radius = int(pow((pow((circle_data[0][0] - circle_data[1][0]), 2) + pow(
(circle_data[0][1] - circle_data[1][1]), 2)), 0.5)) + 1
cv.circle(mask, center, radius, (4), -1)
self.JZW_COUNT[3] += 1
jzw_flag[3] = 1
else:
draw.set_color(mask, [rr, cc], [4])
self.JZW_COUNT[3] += 1
jzw_flag[3] = 1
elif i['label'] == 'HC':
draw.set_color(mask, [rr, cc], [5])
self.JZW_COUNT[4] += 1
jzw_flag[4] = 1
elif i['label'] == 'SZ':
draw.set_color(mask, [rr, cc], [6])
self.JZW_COUNT[5] += 1
jzw_flag[5] = 1
elif i['label'] == 'HH':
draw.set_color(mask, [rr, cc], [7])
self.JZW_COUNT[6] += 1
jzw_flag[6] = 1
elif i['label'] == 'XW' or i['label'] == 'xw':
draw.set_color(mask, [rr, cc], [8])
self.JZW_COUNT[7] += 1
jzw_flag[7] = 1
elif i['label'] == 'XQL':
draw.set_color(mask, [rr, cc], [9])
self.JZW_COUNT[8] += 1
jzw_flag[8] = 1
else:
print(i['label'])
print(imgpath)
# draw.set_color(mask, [rr, cc], [4])
self.img_COUNT = np.array(self.img_COUNT) + np.array(jzw_flag)
return mask
# def json2voc_Large(self, imgpath):
# img = cv.imread(self.path + imgpath, cv.IMREAD_GRAYSCALE)
# mask = np.zeros(img.shape, np.uint8)
# # mask = mask + 255
# with open(self.path + imgpath[:-3] + 'json', encoding='utf-8') as a:
# # 读取文件
# result = json.load(a)
# # 获取姓名
# shapes = result.get('shapes')
# for i in shapes:
# crack = i['points']
# area = cv.contourArea(np.array(crack, dtype=np.int64))
#
# if area > 2000:
# # print(i['label'], "------------", area)
# X = []
# Y = []
# for j in range(len(crack)):
# crack[j][0] = int(crack[j][0])
# crack[j][1] = int(crack[j][1])
# X.append(crack[j][1])
# Y.append(crack[j][0])
# rr, cc = draw.polygon(np.array(X), np.array(Y))
# if i['label'] == 'S':
# draw.set_color(mask, [rr, cc], [1])
# elif i['label'] == 'B':
# draw.set_color(mask, [rr, cc], [2])
# elif i['label'] == 'C':
# draw.set_color(mask, [rr, cc], [3])
# elif i['label'] == 'D':
# if i['shape_type'] == 'circle':
# circle_data = i['points']
# center = (int(circle_data[0][0]), int(circle_data[0][1]))
# radius = int(pow((pow((circle_data[0][0] - circle_data[1][0]), 2) + pow(
# (circle_data[0][1] - circle_data[1][1]), 2)), 0.5)) + 1
# cv.circle(mask, center, radius, (4), -1)
# else:
# draw.set_color(mask, [rr, cc], [4])
# elif i['label'] == 'HC':
# draw.set_color(mask, [rr, cc], [5])
# # else:
# # draw.set_color(mask, [rr, cc], [4])
# return mask
def enhance(self, img, mask, name):
total_name = "total"
JPEGImages_name = os.path.join(self.save_path, "total/JPEGImages")
SegmentationClass_name = os.path.join(self.save_path, "total/SegmentationClass")
if not os.path.exists(os.path.join(self.save_path, total_name)):
os.mkdir(os.path.join(self.save_path, total_name))
if not os.path.exists(JPEGImages_name):
os.mkdir(JPEGImages_name)
if not os.path.exists(SegmentationClass_name):
os.mkdir(SegmentationClass_name)
cv.imwrite(JPEGImages_name + "/" + name, img)
cv.imwrite(SegmentationClass_name + "/" + name[:-3] + "png", mask)
# 旋转(90, 180, 270)
# img90 = cv.rotate(img, cv.ROTATE_90_CLOCKWISE)
# mask90 = cv.rotate(mask, cv.ROTATE_90_CLOCKWISE)
# saveimg = JPEGImages_name + "/" + name[:-4] + '-rotate-' + '90' + '.jpg'
# savemask = SegmentationClass_name + "/" + name[:-4] + '-rotate-' + '90' + '.png'
# cv.imwrite(saveimg, img90)
# cv.imwrite(savemask, mask90)
# 翻转(水平, 垂直)
# imgflip0 = cv.flip(img, 0)
# maskflip0 = cv.flip(mask, 0)
# saveimg = JPEGImages_name + "/" + name[:-4] + '-flip' + '.jpg'
# savemask = SegmentationClass_name + "/" + name[:-4] + '-flip' + '.png'
# cv.imwrite(saveimg, imgflip0)
# cv.imwrite(savemask, maskflip0)
# img180, _ = rotate_image(img, angle=180)
# mask180, _ = rotate_image(mask, angle=180)
# saveimg = JPEGImages_name + "/" + name[:-4] + 'rotate' + '180' + '.jpg'
# savemask = SegmentationClass_name + "/" + name[:-4] + 'rotate' + '180' + '.png'
# cv.imwrite(saveimg, img180)
# cv.imwrite(savemask, mask180)
#
# img270, _ = rotate_image(img, angle=270)
# mask270, _ = rotate_image(mask, angle=270)
# saveimg = JPEGImages_name + "/" + name[:-4] + 'rotate' + '270' + '.jpg'
# savemask = SegmentationClass_name + "/" + name[:-4] + 'rotate' + '270' + '.png'
# cv.imwrite(saveimg, img270)
# cv.imwrite(savemask, mask270)
def crop(self, crop_type):
crop_name = "crop"
JPEGImages_name = os.path.join(self.save_path, "crop/JPEGImages")
SegmentationClass_name = os.path.join(self.save_path, "crop/SegmentationClass")
if not os.path.exists(os.path.join(self.save_path, crop_name)):
os.mkdir(os.path.join(self.save_path, crop_name))
if not os.path.exists(JPEGImages_name):
os.mkdir(JPEGImages_name)
if not os.path.exists(SegmentationClass_name):
os.mkdir(SegmentationClass_name)
c = 512
img_total_path = os.path.join(self.save_path, "total/JPEGImages")
png_total_path = os.path.join(self.save_path, "total/SegmentationClass")
if not os.path.exists(img_total_path):
os.mkdir(img_total_path)
if not os.path.exists(png_total_path):
os.mkdir(png_total_path)
imgs = os.listdir(img_total_path)
for item in imgs:
if item.endswith('jpg'):
_img = img_total_path + "/" + item
_png = png_total_path + "/" + item[:-3] + 'png'
img = cv.imread(_img)
png = cv.imread(_png, cv.IMREAD_GRAYSCALE)
# ret, png = cv.threshold(png, 1, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
count_h = int(img.shape[0] / c)
count_w = int(img.shape[1] / c)
height = c
width = c
w2 = 0
h2 = 0
for j in range(count_h):
for i in range(count_w):
if (i + 1) * width <= img.shape[1]:
if (j + 1) * height <= img.shape[0]:
w2 = (i + 1) * width
h2 = (j + 1) * height
elif (j + 1) * height > img.shape[0]:
w2 = (i + 1) * width
h2 = img.shape[0]
else:
if (j + 1) * height <= img.shape[0]:
w2 = img.shape[1]
h2 = (j + 1) * height
elif (j + 1) * height > img.shape[0]:
w2 = img.shape[1]
h2 = img.shape[0]
imgcrop = img[(h2 - c):h2, (w2 - c):w2]
pngcrop = png[(h2 - c):h2, (w2 - c):w2]
# pngcrop = cv.cvtColor(pngcrop, cv.COLOR_BGR2GRAY)
imgcroppath = JPEGImages_name + '/' + item[:-4] + '_' + str(j) + str(i) + '.jpg'
pngcroppath = SegmentationClass_name + '/' + item[:-4] + '_' + str(j) + str(i) + '.png'
if crop_type == "nobg":
# ret, pngcrop_INV = cv.threshold(pngcrop, 30, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
# contours, hierarchy = cv.findContours(pngcrop_INV, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
# if len(contours) > 0:
# cv.drawContours(img, contours, -1, (0, 0, 255), 10)
# cv.imshow("crop", pngcrop_INV)
# cv.waitKey(0)
# cv.imwrite(imgcroppath, imgcrop)
# cv.imwrite(pngcroppath, pngcrop)
max_value = np.min(pngcrop)
if max_value < 255:
# print(str(max_value) + "----max_value")
cv.imwrite(imgcroppath, imgcrop)
cv.imwrite(pngcroppath, pngcrop)
else:
cv.imwrite(imgcroppath, imgcrop)
cv.imwrite(pngcroppath, pngcrop)
# if max_value == 3:
# a = 1
print(item + "----Crop")
print("----------------------")
def crop_4(self, crop_type):
crop_name = "crop"
JPEGImages_name = os.path.join(self.save_path, "crop/JPEGImages")
SegmentationClass_name = os.path.join(self.save_path, "crop/SegmentationClass")
if not os.path.exists(os.path.join(self.save_path, crop_name)):
os.mkdir(os.path.join(self.save_path, crop_name))
if not os.path.exists(JPEGImages_name):
os.mkdir(JPEGImages_name)
if not os.path.exists(SegmentationClass_name):
os.mkdir(SegmentationClass_name)
img_total_path = os.path.join(self.save_path, "total/JPEGImages")
png_total_path = os.path.join(self.save_path, "total/SegmentationClass")
if not os.path.exists(img_total_path):
os.mkdir(img_total_path)
if not os.path.exists(png_total_path):
os.mkdir(png_total_path)
imgs = os.listdir(img_total_path)
for item in imgs:
if item.endswith('jpg'):
c = 1024
_img = img_total_path + "/" + item
_png = png_total_path + "/" + item[:-3] + 'png'
img = cv.imread(_img)
png = cv.imread(_png, cv.IMREAD_GRAYSCALE)
# ret, png = cv.threshold(png, 1, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
count_h = int(img.shape[0] / c)
count_w = int(img.shape[1] / 1224)
height = c
width = 1224
w2 = 0
h2 = 0
for j in range(count_h):
for i in range(count_w):
if (i + 1) * width <= img.shape[1]:
if (j + 1) * height <= img.shape[0]:
w2 = (i + 1) * width
h2 = (j + 1) * height
elif (j + 1) * height > img.shape[0]:
w2 = (i + 1) * width
h2 = img.shape[0]
else:
if (j + 1) * height <= img.shape[0]:
w2 = img.shape[1]
h2 = (j + 1) * height
elif (j + 1) * height > img.shape[0]:
w2 = img.shape[1]
h2 = img.shape[0]
imgcrop = img[(h2 - c):h2, (w2 - 1224):w2]
pngcrop = png[(h2 - c):h2, (w2 - 1224):w2]
# pngcrop = cv.cvtColor(pngcrop, cv.COLOR_BGR2GRAY)
imgcroppath = JPEGImages_name + '/' + item[:-4] + '_' + str(j) + str(i) + '.jpg'
pngcroppath = SegmentationClass_name + '/' + item[:-4] + '_' + str(j) + str(i) + '.png'
if crop_type == "nobg":
# ret, pngcrop_INV = cv.threshold(pngcrop, 30, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
# contours, hierarchy = cv.findContours(pngcrop_INV, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
# if len(contours) > 0:
# cv.drawContours(img, contours, -1, (0, 0, 255), 10)
# cv.imshow("crop", pngcrop_INV)
# cv.waitKey(0)
# cv.imwrite(imgcroppath, imgcrop)
# cv.imwrite(pngcroppath, pngcrop)
max_value = np.max(pngcrop)
if max_value > 0:
# print(str(max_value) + "----max_value")
cv.imwrite(imgcroppath, imgcrop)
cv.imwrite(pngcroppath, pngcrop)
else:
cv.imwrite(imgcroppath, imgcrop)
cv.imwrite(pngcroppath, pngcrop)
# if max_value == 3:
# a = 1
print(item + "----Crop")
print("----------------------")
def info(self):
print("-----------夹杂物目标数量统计-----------")
print("A类: ", str(self.JZW_COUNT[0]), "个")
print("B类: ", str(self.JZW_COUNT[1]), "个")
print("C类: ", str(self.JZW_COUNT[2]), "个")
print("D类: ", str(self.JZW_COUNT[3]), "个")
print("灰尘: ", str(self.JZW_COUNT[4]), "个")
print("水渍: ", str(self.JZW_COUNT[5]), "个")
print("划痕: ", str(self.JZW_COUNT[6]), "个")
print("纤维: ", str(self.JZW_COUNT[7]), "个")
print("镶嵌料: ", str(self.JZW_COUNT[8]), "个")
print("-----------夹杂物图片数量统计-----------")
print("A类: ", str(self.img_COUNT[0]), "张")
print("B类: ", str(self.img_COUNT[1]), "张")
print("C类: ", str(self.img_COUNT[2]), "张")
print("D类: ", str(self.img_COUNT[3]), "张")
print("灰尘: ", str(self.img_COUNT[4]), "张")
print("水渍: ", str(self.img_COUNT[5]), "张")
print("划痕: ", str(self.img_COUNT[6]), "张")
print("纤维: ", str(self.img_COUNT[7]), "张")
print("镶嵌料: ", str(self.img_COUNT[8]), "张")
if __name__ == '__main__':
path = r'D:\pic\demo\06040012\src\\'#原图加json
savepath = r'D:\pic\demo\06040012\png\\'# png
P1 = Process()
P1.loadjson(path, savepath)
P1.run("nobg")
P1.info()
# 240124-B-32-------38
# B17-B23
# JT