gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:06:08 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com