OPENCV 图像的平均值仅使用阈值以下的值

OPENCV mean value of image using only values under a threshold

我有图像中一行灰度图像 (​​0-255) 的强度值。我想应用像素居中,所以我从所有强度值中减去平均值。但我不想包含高于 200 的值。不遍历图像的最佳方法是什么?我尝试了 cv2.mean(input, mask) 但无法正确设置掩码。我也尝试了 statistics 库中的 mean(x for x in mid_line if x < 200),但结果平均值不正确。

您可以使用 cv2.threshold 创建遮罩。您需要将所有高于 200 的值设置为 0,将低于 200 的值设置为 255,因此,需要将标志设置为 cv2.THRESH_BINARY_INV.

import cv2

# assuming row has your values
ret, thresh = cv2.threshold(row, 200, 255, cv2.THRESH_BINARY_INV)
result = cv2.mean(row, thresh)

这只会计算小于等于 200 的像素的平均值。