如何用4像素扩展特定的颜色斑点?

问题描述

我正在尝试将顶部布料分割扩展为4个像素。如何使用Opencv做到这一点?

enter image description here

下面是图像的灰度版本。

enter image description here

解决方法

签出

import numpy as np
import cv2


winname = 'clothes'
erode_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11))
# dilate_kernel size = (<desired expansion> + (<erode_kernel size> - 1) / 2) * 2 + 1


def on_mouse(event,x,y,flag,img):
    if event == cv2.EVENT_LBUTTONUP:
        # get only pixels of selected color with black background
        color = img[y][x]
        selection = np.where(img == color,img,0)

        # split image and selection by channels as next code doesn't work
        #   with multichannel images
        channels_img = cv2.split(img)
        channels_sel = cv2.split(selection)
        for i in range(len(channels_sel)):
            # remove noise pixels of the same color
            channels_sel[i] = cv2.erode(channels_sel[i],erode_kernel)

            # now expand selected blob
            # note that dilation kernel must compensate erosion so 
            #   add erosion kernel size to it
            channels_sel[i] = cv2.dilate(channels_sel[i],dilate_kernel)

            # replace fragment on original image with expanded blob
            mask = cv2.threshold(channels_sel[i],255,cv2.THRESH_BINARY_INV)[1]
            channels_img[i] = cv2.bitwise_and(channels_img[i],mask)
            channels_img[i] = cv2.bitwise_or(channels_img[i],channels_sel[i])

        # merge processed channels back
        img = cv2.merge(channels_img)
        selection = cv2.merge(channels_sel)
        cv2.imshow(winname,img)
        cv2.imshow('selection',selection)


img = cv2.imread('images/clothes.png')
cv2.imshow(winname,img)
cv2.setMouseCallback(winname,on_mouse,img)
cv2.waitKey()

face segment t-shirt segment skirt segment

,

这是一种方法:

  • 将图像加载为灰度
  • 提取像素== 4
  • 使用中值滤波器消除噪声
  • 利用盘状结构元素对提取区域进行形态学扩张
  • 通过将4放在膨胀像素所在的位置,并将原始图像放在其他位置来创建输出图像
  • 保存

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image
im = cv2.imread('clothes.png',cv2.IMREAD_GRAYSCALE)

# Extract top cloth,i.e. just class 4
topCloth = np.where(im==4,0).astype(np.uint8)

# Remove outlying noise pixels
topClothSmooth = cv2.medianBlur(topCloth,5)

# Create disk-shaped structuring element and dilate
SE = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))
dilated = cv2.dilate(topClothSmooth,SE)

# Apply dilated class back to original image,so where dilated > 0,put 4,elsewhere put original
res = np.where(dilated>0,4,im)

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

结果如下:

enter image description here

以下是原始版本和结果之间的动画版本:

enter image description here