2024-03-29 11:51:02 发布
网友
假设我有以下几组图像:
我想取中心坐标蒙版,即圆形蒙版,其中包含单元格:
最终分离细胞
如何使用Python3和opencv实现这些功能
检测物体的轮廓
循环浏览轮廓,找到包围图像中心的轮廓
使用该轮廓,为图像创建遮罩并遮罩图像
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)
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
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)
get_masked
img = cv2.imread("blobs.png") cv2.imshow("img_processed", get_masked(img)) cv2.waitKey(0)
概念
检测物体的轮廓
循环浏览轮廓,找到包围图像中心的轮廓
使用该轮廓,为图像创建遮罩并遮罩图像
代码
输出
解释
process
函数处理图像),并且对于轮廓面积大于100
(滤除噪声)的每个轮廓,检查图像的中心是否在轮廓内(通过检查调用cv2.pointPolygonTest
的结果是否返回正数来完成),创建掩码,掩码图像并返回掩码图像:get_masked
函数define before并显示图像:相关问题 更多 >
编程相关推荐