使用Python3和opencv从遮罩图像获取中心遮罩

2024-03-29 11:51:02 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下几组图像:

enter image description here

我想取中心坐标蒙版,即圆形蒙版,其中包含单元格:

enter image description here

最终分离细胞

enter image description here

如何使用Python3和opencv实现这些功能


Tags: 图像功能圆形中心opencvpython3细胞
1条回答
网友
1楼 · 发布于 2024-03-29 11:51:02

概念

  1. 检测物体的轮廓

  2. 循环浏览轮廓,找到包围图像中心的轮廓

  3. 使用该轮廓,为图像创建遮罩并遮罩图像

代码

import cv2
import numpy as np

def process(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_canny = cv2.Canny(img_gray, 0, 50)
    img_dilate = cv2.dilate(img_canny, None, iterations=1)
    img_erode = cv2.erode(img_dilate, None, iterations=1)
    return img_erode

def get_masked(img):
    h, w, _ = img.shape
    center = h // 2, w // 2
    contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        if cv2.contourArea(cnt) > 100:
            if cv2.pointPolygonTest(cnt, center, False) > 0:
                mask = np.zeros((h, w), 'uint8')
                cv2.drawContours(mask, [cnt], -1, 255, -1) 
                return cv2.bitwise_and(img, img, mask=mask)

img = cv2.imread("blobs.png")
cv2.imshow("img_processed", get_masked(img))
cv2.waitKey(0)

输出

enter image description here

解释

  1. 导入必要的库:
import cv2
import numpy as np
  1. 定义一个函数,将图像处理为二值图像,以便在检测图像轮廓时获得最佳结果:
def process(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_canny = cv2.Canny(img_gray, 0, 50)
    img_dilate = cv2.dilate(img_canny, None, iterations=1)
    img_erode = cv2.erode(img_dilate, None, iterations=1)
    return img_erode
  1. 定义一个函数,该函数将循环通过图像的轮廓(使用之前定义的process函数处理图像),并且对于轮廓面积大于100(滤除噪声)的每个轮廓,检查图像的中心是否在轮廓内(通过检查调用cv2.pointPolygonTest的结果是否返回正数来完成),创建掩码,掩码图像并返回掩码图像:
def get_masked(img):
    h, w, _ = img.shape
    center = h // 2, w // 2
    contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        if cv2.contourArea(cnt) > 100:
            if cv2.pointPolygonTest(cnt, center, False) > 0:
                mask = np.zeros((h, w), 'uint8')
                cv2.drawContours(mask, [cnt], -1, 255, -1) 
                return cv2.bitwise_and(img, img, mask=mask)
  1. 最后,读入图像,应用get_masked函数define before并显示图像:
img = cv2.imread("blobs.png")
cv2.imshow("img_processed", get_masked(img))
cv2.waitKey(0)

相关问题 更多 >