二值mask图像 + RGB原图 生成可视化分割结果; 从二值mask获取分割轮廓点

1 篇文章 0 订阅
本文介绍了使用Python和OpenCV进行图像分割,通过可视化二值mask获取物体轮廓的方法,展示了如何读取图像、修改颜色并显示轮廓。同时涵盖了cv2.findContours函数的基本用法和实例操作。
摘要由CSDN通过智能技术生成

 可视化分割结果:

import cv2
import numpy as np
from tqdm import tqdm
from PIL import Image
from pathlib import Path

image_root = Path('data/leftImg8bit/test/qdu')
mask_root = Path('evaluation_logs/origin')
save_root = Path('evaluation_logs/visual')

for mask in tqdm(mask_root.iterdir()):
    name = mask.name
    imagepath = image_root / name

    # mask = Image.open(mask)
    # image = Image.open(imagepath)
    # print(mask.mode)        # L
    # print(image.mode)       # RGB
    mask = cv2.imread(str(mask), cv2.IMREAD_GRAYSCALE)
    image = cv2.imread(str(imagepath), cv2.IMREAD_COLOR)
    # print(mask.shape)       # 1080 1920
    # print(image.shape)      # 1080 1920 3


    image = image.astype(np.float64)
    image[mask > 100] = (image[mask > 100] * 0.6).astype(np.int64)
    image[mask > 100] += np.array([100,0,0], dtype=np.int64)

    sp = save_root / name
    cv2.imwrite(str(sp), image)

从二值mask获取分割轮廓点:cv2.findcontours()

import cv2
from tqdm import tqdm
from pathlib import Path

mask_root = Path('evaluation_logs/origin')
image_root = Path('data/leftImg8bit/test/qdu')


for maskpath in tqdm(mask_root.iterdir()):
    name = maskpath.name

    mask = cv2.imread(str(maskpath), cv2.IMREAD_GRAYSCALE)
    print(mask.shape)       # 1080 1920

    contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    print(maskpath)
    # print(type(contours), len(contours))
    # print(type(contours[0]), contours[0].shape)
    # print(type(contours[1]), contours[1].shape)
    # print(type(hierarchy), hierarchy)

    outlines = []
    for cnt in contours:
        # print(type(cnt), cnt.shape)
        cnt = cnt[::,0,:]
        # print(type(cnt), cnt.shape)
        # print(cnt)
        cnt = cnt.tolist()
        # print(cnt)
        outlines.append(cnt)


    imagepath = image_root / name
    image = cv2.imread(str(imagepath), cv2.IMREAD_COLOR)

    for otl in outlines:

        for point in otl:
            cv2.circle(image, point, 1, (255,0,0))

    cv2.imshow('', image)
    cv2.waitKey(0)
    break

参考:python-opencv2利用cv2.findContours()函数来查找检测物体的轮廓_hjxu2016的博客-CSDN博客_cv2.findcontours

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值