'Questions about the open cv pixel mean value
I want to find a program that reads an image in open cv and outputs m1-m2 when the average of pixels with pixel values greater than 100 is m1 and the average of pixels less than 100 is m2.
m1 = img.mean()
print(m1)
I tried the above method, but I couldn't find the average value of pixels larger than 100. I'd appreciate your help.
Solution 1:[1]
Assuming you want m1 to be the average for values above 100 and m2 to be the average of values below 100, you could do something like this:
import cv2
img = cv2.imread("demo.png", cv2.IMREAD_GRAYSCALE)
# Obtain masks
__, m1_mask = cv2.threshold(
src=img,
thresh=100,
maxval=255,
type=cv2.THRESH_BINARY
)
__, m2_mask = cv2.threshold(
src=img,
thresh=99,
maxval=255,
type=cv2.THRESH_BINARY_INV
)
# Calculate mean
ret = cv2.mean(src=img, mask=m1_mask)
m1 = ret[0]
ret = cv2.mean(src=img, mask=m2_mask)
m2 = ret[0]
print(f"Average of m1: {m1}\nAverage of m2: {m2}")
If however you want m1 to be the average of values greater than 100 and m2 to be the average of values less than or equal to 100, you could remove the second threshold call and instead just invert the mask:
import cv2
img = cv2.imread("demo.png", cv2.IMREAD_GRAYSCALE)
# Obtain masks
__, m1_mask = cv2.threshold(
src=img,
thresh=100,
maxval=255,
type=cv2.THRESH_BINARY
)
m2_mask = 255 - m1_mask # https://stackoverflow.com/a/7733886/6946577
# Calculate mean
ret = cv2.mean(src=img, mask=m1_mask)
m1 = ret[0]
ret = cv2.mean(src=img, mask=m2_mask)
m2 = ret[0]
print(f"Average of m1: {m1}\nAverage of m2: {m2}")
See OpenCV documentation for mean and threshold methods, as well as the S.O. answer regarding mask inversion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ljden |
