当前位置:   article > 正文

python根据坐标生成mask_在图像中通过一系列坐标生成掩膜

在图像中通过一系列坐标生成掩膜
# -*- coding : UTF-8 -*-
# @file   : cvt_xml2mask.py
# @Time   : 2021/6/2 20:44
# @Author : wmz

import cv2
import numpy as np

# 输入图片
imgName = '0001009.jpg'

img = cv2.imread(imgName)

# 展示原图
cv2.imshow("img", img)
# 创建掩膜
mask = np.zeros(img.shape[:2], dtype=np.uint8)
polygon = np.array([[27, 175], [510, 152], [519, 471], [24, 474]], np.int32) # 坐标为顺时针方向
cv2.fillConvexPoly(mask, polygon, (255, 255, 255))
image = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)
# 展示掩膜图片
cv2.imshow("mask", mask)
# 展示添加掩膜效果图片
cv2.imshow("image", image)

cv2.waitKey()
cv2.destroyAllWindows()
cv2.imwrite('01.png',mask)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

测试效果:
在这里插入图片描述
将路径下的xml格式标注的坐标生成mask

# -*- coding : UTF-8 -*-
# @file   : cvt_img_xml2mask.py
# @Time   : 2021/6/2 22:37
# @Author : wmz

import os
import xml.dom.minidom
from PIL import Image
import cv2
import numpy as np


def getFiles(path, suffix):
    return [os.path.join(root, file) for root, dirs, files in os.walk(path) for file in files if file.endswith(suffix)]


def cvt_xml_img_mask(src_dir, dst_dir):
    filelist = getFiles(src_dir, '.xml')
    # filelist = os.listdir(srcdir)
    log_info_file = open(logfile, 'w', encoding='utf-8')
    for i in range(0, len(filelist)):
        xmlfile = os.path.join(src_dir, filelist[i])
        imgfilename = xmlfile.replace(".xml", ".jpg")
        maskimgfilename = xmlfile.replace(src_dir, dst_dir).replace(".xml", "_matte.png")
        # 读取图像 标签
        # img = cv2.imread(imgfilename) # 中文路径不能解析
        img = cv2.imdecode(np.fromfile(imgfilename, dtype=np.uint8), cv2.IMREAD_COLOR)
        height, width, c = img.shape
        # write file
        output_name_dir = maskimgfilename.rsplit('\\', 1)[0]
        if not os.path.exists(output_name_dir):
            os.makedirs(output_name_dir)
        content_tree = xml.dom.minidom.parse(xmlfile)
        content = content_tree.documentElement
        # print(content)
        LineInfos = content.getElementsByTagName('LineInfo')
        ltx, lty, lbx, lby, rtx, rty, rbx, rby = 0, 0, 0, 0, 0, 0, 0, 0
        for lineinfo in LineInfos:
            if lineinfo.hasAttribute("ptLTX"):
                ltx = int(lineinfo.getAttribute("ptLTX"))
                # print("LTX:", ltx)
            if lineinfo.hasAttribute("ptLTY"):
                lty = int(lineinfo.getAttribute("ptLTY"))
                # print("LTY:", lty)
            if lineinfo.hasAttribute("ptLBX"):
                lbx = int(lineinfo.getAttribute("ptLBX"))
                # print("LBX:", lbx)
            if lineinfo.hasAttribute("ptLBY"):
                lby = int(lineinfo.getAttribute("ptLBY"))
                # print("LBY:", lby)
            if lineinfo.hasAttribute("ptRTX"):
                rtx = int(lineinfo.getAttribute("ptRTX"))
                # print("RTX:", rtx)
            if lineinfo.hasAttribute("ptRTY"):
                rty = int(lineinfo.getAttribute("ptRTY"))
                # print("RTY:", rty)
            if lineinfo.hasAttribute("ptRBX"):
                rbx = int(lineinfo.getAttribute("ptRBX"))
                # print("RBX:", rbx)
            if lineinfo.hasAttribute("ptRBY"):
                rby = int(lineinfo.getAttribute("ptRBY"))
                # print("RBY:", rby)
        # 创建掩膜
        mask = np.zeros(img.shape[:2], dtype=np.uint8)
        polygon = np.array([[ltx, lty], [rtx, rty], [rbx, rby], [lbx, lby]], np.int32)  # 坐标为顺时针方向
        cv2.fillConvexPoly(mask, polygon, (255, 255, 255))
        # cv2.imwrite('01.png', mask)
        cv2.imencode('.png', mask)[1].tofile(maskimgfilename)


if __name__ == '__main__':
    # src_directory = os.getcwd()
    # dst_directory = os.getcwd()
    logfile = r"F:\dataset\qyhk\log.txt"
    src_directory = r"F:\dataset\qyhk\images"
    dst_directory = r"F:\dataset\qyhk\mask"
    cvt_xml_img_mask(src_directory, dst_directory)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

参考:【Python-Opencv】cv2.fillPoly为非凸任意形状填充,cv2.fillConvexPoly为凸填充

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/285047
推荐阅读
相关标签
  

闽ICP备14008679号