【问题标题】:How to calculate the mean index in array with NumPy如何使用 NumPy 计算数组中的平均索引
【发布时间】:2017-10-15 21:10:57
【问题描述】:

如何计算数组 nums 的平均索引 T 以最小化

abs(sum(nums[:T])-sum(nums[T:]))

【问题讨论】:

  • 产生最小的样本数据和预期的输出?
  • 你怎么能假设情况如此呢? [1000, 2000, 3, 1],在这里工作的T 是什么?此外,这看起来像 XY Problem
  • 感谢您的更改。不过,看起来很像提到的 XY 问题。不管怎样,到目前为止你想到了什么?我敢肯定你不是第一次来这里问这个问题,你肯定已经有了一些想法,值得讨论。例如,如果有一个辅助变量来保存 nums 的运行累积总和呢?
  • 其实我是用np.average(range(0, 256), weights=histogram)在一张灰度图的直方图中找一个阈值但是失败了,结果不是直方图的平均指数。

标签: python numpy average


【解决方案1】:

您尝试解决的特定问题有一个众所周知的解决方案,称为 Otsu 方法。以下代码来自https://learnopencv.com/otsu-thresholding-with-opencv/

# Set total number of bins in the histogram
bins_num = 256

# Get the image histogram
hist, bin_edges = np.histogram(image, bins=bins_num)

# Get normalized histogram if it is required
if is_normalized:
    hist = np.divide(hist.ravel(), hist.max())

# Calculate centers of bins
bin_mids = (bin_edges[:-1] + bin_edges[1:]) / 2.

# Iterate over all thresholds (indices) and get the probabilities w1(t), w2(t)
weight1 = np.cumsum(hist)
weight2 = np.cumsum(hist[::-1])[::-1]

# Get the class means mu0(t)
mean1 = np.cumsum(hist * bin_mids) / weight1
# Get the class means mu1(t)
mean2 = (np.cumsum((hist * bin_mids)[::-1]) / weight2[::-1])[::-1]

inter_class_variance = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2

# Maximize the inter_class_variance function val
index_of_max_val = np.argmax(inter_class_variance)

threshold = bin_mids[:-1][index_of_max_val]
print("Otsu's algorithm implementation thresholding result: ", threshold)

如果您需要应用阈值,那就更容易了。改编自https://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html

import cv2

image_blurred = cv2.GaussianBlur(image,(5,5),0)
otsu_threshold, image_result = cv2.threshold(image_blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

根据您的需要,您可能还想查看自适应阈值,这是一种更本地化到图像中较小区域的阈值。

import cv2

image_blurred = cv2.GaussianBlur(image,(5,5),0)
thresh = cv2.adaptiveThreshold(image_blurred , 255,
    cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, blockSize=11, C=2)

【讨论】:

    【解决方案2】:

    假设它是一个排序数组,否则这没有多大意义:

    numpy.searchsorted(nums, numpy.mean(nums))

    https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.searchsorted.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2017-02-16
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2013-11-24
      • 2019-07-30
      相关资源
      最近更新 更多