python - 如何访问凸包内的像素?

标签 python image opencv contour image-segmentation

一旦我们获得了图像的凸包,他们是否可以通过任何方式访问位于凸包内的像素。

import numpy as np
import cv2
import PIL

usg = cv2.imread("1.jpg",0)

ret, threshold = cv2.threshold(usg, 10,255,cv2.THRESH_BINARY)

_,contours,_ = cv2.findContours(threshold,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)            
hull = [cv2.convexHull(c) for c in contours]

final = cv2.drawContours(usg,hull,-1,(255,255,255))

这里,final 给出了图像的凸包。之后,我想访问船体内部的像素。

最佳答案

如果你已经有了绘制的凸包,你可以简单地使用 NumPy 的 boolean array indexing访问凸包内的像素。

下面是一些示例代码:

import cv2
import numpy as np

# Set up dummy image
img = np.zeros((400, 400, 3), np.uint8)
cv2.fillPoly(img, np.array([[[20, 20], [120, 40], [280, 30], [280, 350], [140, 320], [30, 380]]]), (0, 0, 255))

# Threshold image
_, img_thr = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 10, 255, cv2.THRESH_BINARY)

# Find contours: OpenCV 4.x
contours, _ = cv2.findContours(img_thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Find contours: OpenCV 3.x
#_, contours, _ = cv2.findContours(img_thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Convex hulls from contours in list
hulls = [cv2.convexHull(c) for c in contours]

# Draw convex hull of first contour
hull = np.zeros(img_thr.shape, np.uint8)
hull = cv2.drawContours(hull, np.array([np.squeeze(hulls[0])]), -1, 255, cv2.FILLED)

# Access pixels inside convex hull; here add some green values to original image
idx = hull == 255
final = img.copy()
final[idx, :] = final[idx, :] + (0, 128, 0)

cv2.imshow('img', img)
cv2.imshow('hull', hull)
cv2.imshow('final', final)
cv2.waitKey(0)
cv2.destroyAllWindows()

这是虚拟图像img:

Image

这就是绘制的凸包hull:

Convex hull

这是最终图像 final,其中 img 中凸包内的像素已被修改:

Final

希望对您有所帮助!

关于python - 如何访问凸包内的像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58875113/

相关文章:

python - 如何通过共享内存将 cv::Mat 发送到 python?

python - 使用python向图像添加黑框

image - 推送图像 Vaadin Java

ios - 如何快速向uiimage添加彩色边框

c++ - OpenCv 的版本号是否有常数?

python - 烤宽面条函数参数的形状不正确

python - 以数字方式检查数组中的数字是否以给定数字开头

python - 传递值的形状是 (3514, 78),索引意味着 (1, 78)

python - Voronoi图的轮廓坐标

android - 我可以从我的 apk 中删除哪个 libopencv_java3.so?