【发布时间】:2023-02-20 10:47:37
【问题描述】:
Inspired by this question and this answer (which isn't very solid) I realized that I often find myself converting to grayscale a color image that is almost grayscale (usually a color scan from a grayscale original). So I wrote a function meant to measure a kind of distance of a color image from grayscale:
import numpy as np
from PIL import Image, ImageChops, ImageOps, ImageStat
def distance_from_grey(img): # img must be a Pillow Image object in RGB mode
img_diff=ImageChops.difference(img, ImageOps.grayscale(img).convert('RGB'))
return np.array(img_diff.getdata()).mean()
img = Image.open('test.jpg')
print(distance_from_grey(img))
The number obtained is the average difference among all pixels of RGB values and their grayscale value, which will be zero for a perfect grayscale image.
What I'm asking to imaging experts is:
- is this approach valid or there are better ones?
- at which distance an image can be safely converted to grayscale without checking it visually?
-
I am not an expert. Intuitively, I would say you need to square the differences before adding them up, and then taking the square root again: Error = 1/N * sqrt(Sum error_i^2). In that case, if some pixels deviate a lot and others don't at all, this is considered worse than if every pixel deviates a little bit.
-
You could use a perceptually uniform colourspace, e.g. JzAzBz, ICtCp, OkLab, convert to Lightness, Chroma, Hue (LCH) representation and check whether the Chroma is close to zero.
-
@KelSolaar Very interesting, I'm studying your comment, I'm sure many would be grateful if you showed how to do in an answer.
-
Not sure exactly what cases you need to discriminate between, but you could consider the saturation in HSV colourspace as an indication of greyness stackoverflow.com/a/74874586/2836621
标签: python colors python-imaging-library grayscale