筛选图片,写JSON文件和复制

筛选图片,写JSON文件和复制

  • 筛选图片,写JSON文件
  • 筛选图片复制

筛选图片,写JSON文件

# coding: utf-8
from PIL import Image, ImageDraw, ImageFont
import os
import shutil
import cv2 as cv
import numpy as np
import json


def zh_ch(string):
    return string.encode("gbk").decode('UTF-8', errors='ignore')


def create_json(path):
    path_dict = {}
    path = path.split('\\')
    file_name = path[-1]
    return path_dict, file_name

def get_root(scr):
    scr = scr.split('\\')
    root_path = os.path.join(*scr[0:-1])
    file_name_1 = scr[-2]
    file_name_0 = scr[-1]
    return root_path, file_name_1, file_name_0

def save_json(filename, dicts):
    filename = filename.replace(':', ':\\')
    with open(filename, 'w') as f:
        json_str = json.dumps(dicts)
        f.write(json_str)


def image_add_text(img1, text, left, top, text_color, text_size):

    if isinstance(img1, np.ndarray):# 判断图片是否为ndarray格式,转为成PIL的格式的RGB图片
        image = Image.fromarray(cv.cvtColor(img1, cv.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(image)# 创建一个可以在给定图像上绘图的对象
    font_style = ImageFont.truetype("font/simsun.ttc", text_size, encoding='utf-8')# 参数依次为 字体、字体大小、编码
    draw.text((left, top), text, text_color, font=font_style)# 参数依次为位置、文本、颜色、字体
    return cv.cvtColor(np.asarray(image), cv.COLOR_RGB2BGR)

def redu(image, ratio):
    width = int(image.shape[1] * ratio)
    height = int(image.shape[0] * ratio)

    image = cv.resize(image, (width, height), interpolation=cv.INTER_AREA)
    return image
def bor_image(image, path, file_name):
    path = path.split('\\')
    if file_name[path[-1]] == 0:
        sen = '无缺陷'
    elif file_name[path[-1]] == 1:
        sen = '有缺陷'
    else:
        sen = '不确定'
    text = path[-1] + '     ' + sen +'\n上一张:w,下一张:s,退出:q\n无缺陷:Backspace,有缺陷:Enter,不确定:{'


    border_img = cv.copyMakeBorder(image, 70, 2, 2, 2, cv.BORDER_CONSTANT, value=[255, 255, 255])
    border_img = image_add_text(border_img, text, 0, 0, (255, 0, 0), 20)
    cv.imshow('image', border_img)

def read_json(file_name):
    with open(file_name, 'rb') as f:
        data = json.load(f)
    return data
def press_key(path_lsit):
    # image = cv.imread(path, cv.IMREAD_GRAYSCALE)
    i = 0
    root_paths = []
    file_dict = {}

    while(0 <= i and i <= len(path_lsit)):
        print(path_lsit[i])
        if 'bmp' not in path_lsit[i]:
            i = i + 1
            continue

        root_path, file_name_1, file_name_0 = get_root(path_lsit[i])
        print(root_path)
        
        if os.path.exists(os.path.join(root_path, 'kuaisu.json')):
            file_dict = read_json(os.path.join(root_path, 'kuaisu.json'))
        else:
            file_dict = {}
            


        image = cv.imdecode(np.fromfile(path_lsit[i], dtype=np.uint8), cv.IMREAD_COLOR)  # 输入图片路径,当路径中有中文时需要采用该语句

        image = cv.transpose(image)
        print(file_dict)
        # 缩小图片
        image = redu(image, 0.55)
        if file_name_0 not in file_dict:
            file_dict[file_name_0] = 0  # 无缺陷
        print(file_dict)
        bor_image(image, path_lsit[i], file_dict)

        key = cv.waitKey(0)
        if key == 115:
            i = i + 1
            save_json(os.path.join(root_path, 'kuaisu.json'), file_dict)
            continue
        if key == 119:
            i = i - 1
            save_json(os.path.join(root_path, 'kuaisu.json'), file_dict)
            continue
        
        if key == 13 or key == 8 or key == 91:#enter/baskspace/{
            if key == 13:
                file_dict[file_name_0] = 1#有缺陷
                bor_image(image, path_lsit[i], file_dict)
                print(file_dict)
            elif key == 8:
                file_dict[file_name_0] = 0#无缺陷
                bor_image(image, path_lsit[i], file_dict)
                print(file_dict)
            else:
                file_dict[file_name_0] = 2#不确定
                bor_image(image, path_lsit[i], file_dict)
                print(file_dict)


            save_json(os.path.join(root_path, 'kuaisu.json'), file_dict)
            

            key = cv.waitKey(0)
            if key == 115:
                    i = i + 1
                    save_json(os.path.join(root_path, 'kuaisu.json'), file_dict)
                    continue
            elif key == 119:
                    i = i - 1
                    save_json(os.path.join(root_path, 'kuaisu.json'), file_dict)
                    continue




        if key == 113:

            save_json(os.path.join(root_path, 'kuaisu.json'), file_dict[file_name_1])
            cv.destroyAllWindows()
            break


if __name__ == '__main__':

    image_root_path = "E:\正在标注"
    path_list = []
    scr_path = []
    # save_path_name = 'H:ImageStore\\ti'

    for root, dirs, files in os.walk(image_root_path):
        for file in files:
            path = os.path.join(root, file)
            if 'bmp' in path:
                path_list.append(path)

    press_key(path_list)

筛选图片复制

# coding: utf-8
from PIL import Image, ImageDraw, ImageFont
import os
import shutil
import cv2 as cv
import numpy as np
import json

# 保留无缺陷的图片

def zh_ch(string):
    return string.encode("gbk").decode('UTF-8', errors='ignore')


def create_json(path):
    path_dict = {}
    path = path.split('\\')
    file_name = path[-1]
    return path_dict, file_name

def get_root(scr):
    scr = scr.split('\\')
    root_path = os.path.join(*scr[0:-1])
    file_name_1 = scr[-2]
    file_name_0 = scr[-1]
    return root_path, file_name_1, file_name_0

def save_json(filename, dicts):
    filename = filename.replace(':', ':\\')
    with open(filename, 'w') as f:
        json_str = json.dumps(dicts)
        f.write(json_str)


def image_add_text(img1, text, left, top, text_color, text_size):

    if isinstance(img1, np.ndarray):# 判断图片是否为ndarray格式,转为成PIL的格式的RGB图片
        image = Image.fromarray(cv.cvtColor(img1, cv.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(image)# 创建一个可以在给定图像上绘图的对象
    font_style = ImageFont.truetype("font/simsun.ttc", text_size, encoding='utf-8')# 参数依次为 字体、字体大小、编码
    draw.text((left, top), text, text_color, font=font_style)# 参数依次为位置、文本、颜色、字体
    return cv.cvtColor(np.asarray(image), cv.COLOR_RGB2BGR)

def redu(image, ratio):
    width = int(image.shape[1] * ratio)
    height = int(image.shape[0] * ratio)

    image = cv.resize(image, (width, height), interpolation=cv.INTER_AREA)
    return image
def bor_image(image, path, file_name):
    path = path.split('\\')
    if file_name[path[-1]] == 0:
        sen = '无缺陷'
    elif file_name[path[-1]] == 1:
        sen = '有缺陷'
    else:
        sen = '不确定'
    text = path[-1] + '     ' + sen +'\n上一张:w,下一张:s,退出:q\n有缺陷:Enter'


    border_img = cv.copyMakeBorder(image, 70, 2, 2, 2, cv.BORDER_CONSTANT, value=[255, 255, 255])
    border_img = image_add_text(border_img, text, 0, 0, (255, 0, 0), 20)
    cv.imshow('image', border_img)

def read_json(file_name):
    with open(file_name, 'rb') as f:
        data = json.load(f)
    return data
def press_key(path_lsit,save_path):
    # image = cv.imread(path, cv.IMREAD_GRAYSCALE)
    i = 0
    root_paths = []
    file_dict = {}

    while(0 <= i and i <= len(path_lsit)):
        print(path_lsit[i])
        if 'bmp' not in path_lsit[i]:
            i = i + 1
            continue

        root_path, file_name_1, file_name_0 = get_root(path_lsit[i])
        print(root_path)
        
        if os.path.exists(os.path.join(root_path, 'kuaisu.json')):
            file_dict = read_json(os.path.join(root_path, 'kuaisu.json'))
        else:
            file_dict = {}
            


        image = cv.imdecode(np.fromfile(path_lsit[i], dtype=np.uint8), cv.IMREAD_COLOR)  # 输入图片路径,当路径中有中文时需要采用该语句

        image = cv.transpose(image)
        print(file_dict)
        # 缩小图片
        image = redu(image, 0.55)
        if file_name_0 not in file_dict:
            file_dict[file_name_0] = 0  # 无缺陷
        print(file_dict)
        bor_image(image, path_lsit[i], file_dict)

        key = cv.waitKey(0)
        if key == 115:
            i = i + 1
            continue
        if key == 119:
            i = i - 1
            continue
        
        if key == 13 or key == 8 or key == 91:#enter/baskspace/{
            if key == 13:
                file_dict[file_name_0] = 1#有缺陷
                bor_image(image, path_lsit[i], file_dict)
                shutil.copy(path_lsit[i], save_path)  # shutil.copy函数放入原文件的路径文件全名  然后放入目标文件夹

            key = cv.waitKey(0)
            if key == 32:  # 空格
                #os.remove(save_path)
                my_list = path_lsit[i].split('\\')
                print(my_list[-1])
                os.remove(save_path+"\\"+my_list[-1])
            if key == 115:
                    i = i + 1
                    continue
            elif key == 119:
                    i = i - 1
                    continue
        if key == 113:
            cv.destroyAllWindows()
            break


if __name__ == '__main__':

    image_root_path = "D:\\Datasets\\defect2\\final9.4\\yes"
    path_list = []
    scr_path = []
    # save_path_name = 'H:ImageStore\\ti'

    for root, dirs, files in os.walk(image_root_path):
        for file in files:
            path = os.path.join(root, file)
            if 'bmp' in path:
                path_list.append(path)

    press_key(path_list,"E:\\Datasets\\defect2\\final9.4\\yes")

你可能感兴趣的:(缺陷检测,json,python,开发语言)