python - 从 numpy 数组中分割一个区域
问题描述
在对图像 I 进行一些处理后,提取了图像的某个区域。 这是 .npy 文件。
segmented_image = np.load('data.npy')
plt.imshow(segmented_image)
现在,我正在尝试crop/segment
P 的区域。我该怎么做?
提前致谢。
解决方案
您可以尝试轮廓过滤。
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)
推荐阅读
- python - 使用 BeautifulSoup 从站点检索到的数据与站点上显示的数据不同
- python - 如何在 Python 中一次处理和执行多个 SQL?
- typescript - 是否可以在打字稿中分离和重用多个函数重载
- android - 生成 x86 版本的 android App Bundle
- python - 在列中查看值并在数据框中更改
- kubernetes - 增加正在运行的 pod 的内存限制
- python - Matplotlib 绘图失败,但 scatter 使用相同的数据成功
- python-3.x - Qt:QFormLayout - 如何从按钮中找到行
- html - 视频播放后 HTML 5 视频显示黑屏
- javascript - 为什么移动设备上的幻灯片之间的图像闪烁?