如何用NumPy计算数组中的平均索引

时间:2017-10-15 21:10:58

标签: python numpy average

如何计算最小化

值的数组nums的平均索引T.
abs(sum(nums[:T])-sum(nums[T:]))

2 个答案:

答案 0 :(得分:0)

假定它是一个有序数组,因为否则这没有多大意义:

printf("\nThe string is : %s",r);

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

答案 1 :(得分:0)

您尝试解决的具体问题有一个众所周知的解决方案,称为 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)