用各种颜色代替圆形斑点

时间:2019-02-11 18:59:31

标签: python image-processing connected-components

我的目的是用与mask_image中的斑点相对应的颜色替换original_image中的斑点。我在这里所做的是找到连接的组件并标记它们,但是我不知道如何找到相应的标记点并替换它。 如何将n个圆放入n个对象中,并用相应的强度填充它们? 任何帮助将不胜感激。

例如,如果遮罩图像中(2,1)中的斑点应使用下面这张图像中相应斑点的颜色绘制。

遮罩图像http://myfair.software/goethe/images/mask.jpg

mask

原始图片http://myfair.software/goethe/images/original.jpg original image

def thresh(img):
    ret , threshold = cv2.threshold(img,5,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    return threshold

def spot_id(img):
    seed_pt = (5, 5)
    fill_color = 0
    mask = np.zeros_like(img)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    for th in range(5, 255):
        prev_mask = mask.copy()
        mask = cv2.threshold(img, th, 255, cv2.THRESH_BINARY)[1]
        mask = cv2.floodFill(mask, None, seed_pt, fill_color)[1]

        mask = cv2.bitwise_or(mask, prev_mask)

        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

    #here I labelled them
    n_centers, labels = cv2.connectedComponents(mask)
    label_hue = np.uint8(892*labels/np.max(labels))
    blank_ch = 255*np.ones_like(label_hue)
    labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
    labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
    labeled_img[label_hue==0] = 0

    print('There are %d bright spots in the image.'%n_centers)

    cv2.imshow("labeled_img",labeled_img)
    return mask, n_centers

image_thresh = thresh(img_greyscaled)
mask, centers = spot_id(img_greyscaled)

1 个答案:

答案 0 :(得分:0)

有一种非常简单的方法可以完成此任务。首先,需要对mask_image中每个点的中心进行采样。接下来,将这种颜色扩展为在同一张图片中填充点。

这里有一些使用PyDIP的代码(因为我比OpenCV更了解,我是作者),我敢肯定,仅使用OpenCV就能完成类似的事情:

import PyDIP as dip
import cv2
import numpy as np

# Load the color image shown in the question
original_image = cv2.imread('/home/cris/tmp/BxW25.png')
# Load the mask image shown in the question
mask_image = cv2.imread('/home/cris/tmp/aqf3Z.png')[:,:,0]

# Get a single colored pixel in the middle of each spot of the mask
colors = dip.EuclideanSkeleton(mask_image > 50, 'loose ends away') * original_image

# Spread that color across the full spot
# (dilation and similar operators like this one don't work with color images,
#  so we apply the operation on each channel separately)
for t in range(colors.TensorElements()):
   colors.TensorElement(t).Copy(dip.MorphologicalReconstruction(colors.TensorElement(t), mask_image))

# Save the result
cv2.imwrite('/home/cris/tmp/so.png', np.array(colors))

output of code above

相关问题