首页 > 解决方案 > 从 numpy 数组中分割一个区域

问题描述

在对图像 I 进行一些处理后,提取了图像的某个区域。 这是 .npy 文件。

segmented_image = np.load('data.npy')
plt.imshow(segmented_image)  

在此处输入图像描述

现在,我正在尝试crop/segmentP 的区域。我该怎么做?

提前致谢。

标签: pythonnumpytensorflowopencvcomputer-vision

解决方案


您可以尝试轮廓过滤。

import cv2
import numpy as np

image = np.load("data.npy")
cv2.imshow("image", image)

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

_, threshold_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY)
cv2.imshow("threshold_image", threshold_image)

contours, hierarchy = cv2.findContours(threshold_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

# here you can apply your conter filter logic
# In this image I can see biggest contur is "p"
selected_contour = max(contours, key=lambda x: cv2.contourArea(x))

mask_image = np.zeros_like(threshold_image)
cv2.drawContours(mask_image, [selected_contour], -1, 255, -1)
cv2.imshow("mask_image", mask_image)

segmented_image = cv2.bitwise_and(image, image, mask=mask_image)
cv2.imshow("segmented_image", segmented_image)

cv2.waitKey(0)


过程图像


推荐阅读