gpt4 book ai didi

python - OpenCV:如何计算中心像素周围窗口的最小值?

转载 作者:太空宇宙 更新时间:2023-11-03 22:51:05 24 4
gpt4 key购买 nike

我试图通过计算图像周围给定窗口的最小值并从原始像素值中减去它来从图像中提取特征。然而,事实证明这是非常缓慢的,因为我正在遍历整个图片。有什么优化的方法吗?

    f = np.asarray(img.shape)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if mask[i][j]==255:
row,col = i,j
begin_row = row - 4
end_row = row + 4
begin_col = col - 4
end_col = col + 4
if begin_row < 0:
begin_row = 0
if begin_col < 0:
begin_col = 0
if end_col > img.shape[1]:
end_col = img.shape[1]
if end_row > img.shape[0]:
end_row = img.shape[0]
window = img[begin_row:end_row, begin_col:end_col]
curr = img.item(row, col)
f.itemset((row, col), curr - window.min())

最佳答案

我不确定我是否正确理解了您的目标:

  • 输入图片I
  • 对于 I 中的每个像素 p 减去周围窗口的最小值(包括原始像素)

然后您可以使用形态过滤器 erode,它的作用类似于最小过滤器:

I_new(p) = I(p) - erode(I, p, window)

在其中参数化 erode 以获得正确的窗口大小和 anchor 。

至于实际实现,您可以使用带有 its erode functionopencv 的 python 版本.它很快,因为它是用 C++/C 实现的。它可能看起来像这样(未经测试):

import cv2
import numpy as np

img = cv2.imread('path/to/image.jpg')

kernel = np.ones((5,5),np.float32)
dst = img - cv2.erode(img,kernel)

最重要的是:避免使用 python 循环遍历图像数组 - 这总是很慢。

关于python - OpenCV:如何计算中心像素周围窗口的最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37587411/

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