【问题标题】:How to overlay segmented image on top of main image in python如何在python中的主图像之上叠加分割图像
【发布时间】:2019-08-20 15:12:22
【问题描述】:

我有一个 RGB 图像和另一个分段图像,其中像素有 3 个值(分段图像)。我想将分割图像叠加在主图像之上,因为分割区域在主图像上形成轮廓,如下图所示。这里分割后的图像像素的值为0、1和2。红色轮廓表示值为1的像素轮廓,黄色轮廓表示值为2的像素轮廓,背景像素值为0。

图片来自论文“Dilated-Inception Net: Multi-Scale FeatureAggregation for Cardiac Right VentricleSegmentation”

这是一个分割图像的例子。

segmented image

背景图片可以是任何图片。我只需要这些矩形计数器在背景图像上显示为类似于上面的红色和黄色线条的两个轮廓。因此,输出将类似于下图。

output image

抱歉,我手工绘制矩形,它们并不精确。我只是想让你了解一下输出。

【问题讨论】:

  • 你的问题,如果有的话,很不清楚。你说你有一个 RGB 图像和另一个分段图像。请问我们两个都可以吗?那么你想对最终图像中的矩形做什么呢?谢谢。
  • 背景图像可以是任何 RGB 图像,这就是为什么我没有添加任何作为主图像的原因。我只需要第二张图像中的矩形计数器覆盖在背景(主)图像上,以使第一张图像中的红线和黄线覆盖心脏 CT 图像的背景图像。
  • 我怎么知道你的分割图像是什么样的?你有红线的 SVG 路径吗?你有没有用红线勾勒出形状的透明背景?您是否获得了每个组织/物体都有纯色的纯色图像?如果您需要一些帮助,通常最好让人们轻松地帮助您。另外,请问什么是“矩形计数器”
  • 我已经添加了我需要的输出。感谢您的帮助。
  • 矩形轮廓是输出图像中的红线和黄线。它们应该被绘制在被分割图像中的矩形占据的像素上。

标签: python opencv image-segmentation imaging


【解决方案1】:

我尝试了四种不同的方法:

  • OpenCV
  • PIL/PillowNumpy
  • 带有 ImageMagick 的命令行
  • skimage 的形态

方法 1 - OpenCV

  • 以灰度打开分段图像
  • 以灰度打开主图像并制作颜色以允许注释
  • 使用cv2.findContours()查找轮廓
  • 遍历轮廓并使用cv2.drawContours()根据分割图像中的标签将每个轮廓以颜色绘制到主图像上。

文档是here

所以,从这张图片开始:

还有这个分割的图像:

对比拉伸时看起来像这样,三明治标记为grey(1),鼻子标记为grey(2)

代码如下:

#!/usr/bin/env python3

import numpy as np
import cv2

# Load images as greyscale but make main RGB so we can annotate in colour
seg  = cv2.imread('segmented.png',cv2.IMREAD_GRAYSCALE)
main = cv2.imread('main.png',cv2.IMREAD_GRAYSCALE)
main = cv2.cvtColor(main,cv2.COLOR_GRAY2BGR)

# Dictionary giving RGB colour for label (segment label) - label 1 in red, label 2 in yellow
RGBforLabel = { 1:(0,0,255), 2:(0,255,255) }

# Find external contours
_,contours,_ = cv2.findContours(seg,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

# Iterate over all contours
for i,c in enumerate(contours):
    # Find mean colour inside this contour by doing a masked mean
    mask = np.zeros(seg.shape, np.uint8)
    cv2.drawContours(mask,[c],-1,255, -1)
    # DEBUG: cv2.imwrite(f"mask-{i}.png",mask)
    mean,_,_,_ = cv2.mean(seg, mask=mask)
    # DEBUG: print(f"i: {i}, mean: {mean}")

    # Get appropriate colour for this label
    label = 2 if mean > 1.0 else 1
    colour = RGBforLabel.get(label)
    # DEBUG: print(f"Colour: {colour}")

    # Outline contour in that colour on main image, line thickness=1
    cv2.drawContours(main,[c],-1,colour,1)

# Save result
cv2.imwrite('result.png',main) 

结果:


方法 2 - PIL/Pillow 和 Numpy

  • 打开分割图像并找到独特的颜色
  • 打开主图像并去饱和
  • 遍历列表中的每个唯一颜色
  • ... 将所有像素设为白色,将所有其他像素设为黑色
  • ...查找边缘并使用边缘作为蒙版在主图像上绘制颜色

代码如下:

#!/usr/bin/env python3

from PIL import Image, ImageFilter
import numpy as np

def drawContour(m,s,c,RGB):
    """Draw edges of contour 'c' from segmented image 's' onto 'm' in colour 'RGB'"""
    # Fill contour "c" with white, make all else black
    thisContour = s.point(lambda p:p==c and 255)
    # DEBUG: thisContour.save(f"interim{c}.png")

    # Find edges of this contour and make into Numpy array
    thisEdges   = thisContour.filter(ImageFilter.FIND_EDGES)
    thisEdgesN  = np.array(thisEdges)

    # Paint locations of found edges in color "RGB" onto "main"
    m[np.nonzero(thisEdgesN)] = RGB
    return m

# Load segmented image as greyscale
seg = Image.open('segmented.png').convert('L')

# Load main image - desaturate and revert to RGB so we can draw on it in colour
main = Image.open('main.png').convert('L').convert('RGB')
mainN = np.array(main)

mainN = drawContour(mainN,seg,1,(255,0,0))   # draw contour 1 in red
mainN = drawContour(mainN,seg,2,(255,255,0)) # draw contour 2 in yellow

# Save result
Image.fromarray(mainN).save('result.png')

你会得到这个结果:


方法 3 - ImageMagick

您也可以从命令行执行相同的操作,而无需编写任何 Python,只需使用安装在大多数 Linux 发行版上且适用于 macOS 和 Windows 的 ImageMagick

#!/bin/bash

# Make red overlay for "1" labels
convert segmented.png -colorspace gray -fill black +opaque "gray(1)" -fill white -opaque "gray(1)" -edge 1 -transparent black -fill red     -colorize 100% m1.gif
# Make yellow overlay for "2" labels
convert segmented.png -colorspace gray -fill black +opaque "gray(2)" -fill white -opaque "gray(2)" -edge 1 -transparent black -fill yellow  -colorize 100% m2.gif
# Overlay both "m1.gif" and "m2.gif" onto main image
convert main.png -colorspace gray -colorspace rgb m1.gif -composite m2.gif -composite result.png


方法 4 - skimage 的形态学

这里我使用形态学来查找1 像素附近的黑色像素和2 像素附近的黑色像素。

#!/usr/bin/env python3

import skimage.filters.rank
import skimage.morphology
import numpy as np
import cv2

# Load images as greyscale but make main RGB so we can annotate in colour
seg  = cv2.imread('segmented.png',cv2.IMREAD_GRAYSCALE)
main = cv2.imread('main.png',cv2.IMREAD_GRAYSCALE)
main = cv2.cvtColor(main,cv2.COLOR_GRAY2BGR)

# Create structuring element that defines the neighbourhood for morphology
selem = skimage.morphology.disk(1)

# Mask for edges of segment 1 and segment 2
# We are basically looking for pixels with value 1 in the segmented image within a radius of 1 pixel of a black pixel...
# ... then the same again but for pixels with a vaue of 2 in the segmented image within a radius of 1 pixel of a black pixel
seg1 = (skimage.filters.rank.minimum(seg,selem) == 0) & (skimage.filters.rank.maximum(seg, selem) == 1)
seg2 = (skimage.filters.rank.minimum(seg,selem) == 0) & (skimage.filters.rank.maximum(seg, selem) == 2)

main[seg1,:] = np.asarray([0, 0,   255]) # Make segment 1 pixels red in main image
main[seg2,:] = np.asarray([0, 255, 255]) # Make segment 2 pixels yellow in main image

# Save result
cv2.imwrite('result.png',main) 

注意:JPEG 是有损的 - 不要将分段图像保存为 JPEG,使用 PNG 或 GIF!

关键字:Python、PIL、Pillow、OpenCV、分割、分段、标记、图像、图像处理、边缘、轮廓、skimage、ImageMagick、scikit-image、形态学、排名、排名过滤器、像素邻接。

【讨论】:

    【解决方案2】:

    如果要在图像顶部显示半透明分割蒙版,skimage 有一个内置的label2rgb() 函数,可以通过标签通道着色:

    输入图像

    from skimage import io, color
    import matplotlib.pyplot as plt
    import numpy as np
    
    seg = np.zeros((256,256)) # create a matrix of zeroes of same size as image
    seg[gt > 0.95] = 1   # Change zeroes to label "1" as per your condition(s)
    seg[zz == 255] = 2   
    
    io.imshow(color.label2rgb(seg,img,colors=[(255,0,0),(0,0,255)],alpha=0.01, bg_label=0, bg_color=None))
    plt.show()
    

    【讨论】:

    • 这很好,但是它将输入图像转换为灰度。如果有问题的图像是 RGB,您是否知道任何替代方案?
    • 参数img 接受RGB 和灰度图像。所以它应该可以正常工作。文档证实了这一点 - scikit-image.org/docs/dev/api/…
    • 它接受 RGB 图像,但在应用分割叠加之前会转换为灰度图像。我希望看到覆盖层后面的原始彩色图像。编辑:我认为这个 saturation arg 可能是关键,但它只存在于 skimage 的 dev 分支上,它似乎没有安装在 colab 上。
    【解决方案3】:

    这些是快速的单行程序,可自动为类别/类整数值选择颜色并在原始图像上执行叠加。

    为整个分割区域着色:

    from skimage import color
    result_image = color.label2rgb(segmentation_results, input_image)
    

    分割区域的颜色轮廓:

    from skimage import segmentation
    result_image = segmentation.mark_boundaries(input_image, segmentation_results, mode='thick')
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 2021-01-28
      • 2020-02-10
      相关资源
      最近更新 更多