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

 可视化分割结果:

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

你可能感兴趣的:(python,cv2,计算机视觉,python,深度学习)