[英]Find If Image Is Bright Or Dark
I would like to know how to write a function in Python 3 using OpenCV which takes in an image and a threshold and returns either 'dark' or 'light' after heavily blurring it and reducing quality (faster the better). 我想知道如何使用OpenCV在Python 3中编写函数,该函数接受图像和阈值,并在严重模糊和降低质量(更快越好)后返回“暗”或“亮”。 This might sound vague , but anything that just works will do. 这听起来可能有些含糊,但是任何可行的方法都可以。
You could try this : 您可以尝试这样:
import imageio
import numpy as np
f = imageio.imread(filename, as_gray=True)
def img_estim(img, thrshld):
is_light = np.mean(img) > thrshld
return 'light' if is_light else 'dark'
print(img_estim(f, 127))
You could try this, considering image
is a grayscale image - 考虑到image
是灰度图像,可以尝试一下-
blur = cv2.blur(image, (5, 5)) # With kernel size depending upon image size
if cv2.mean(blur) > 127: # The range for a pixel's value in grayscale is (0-255), 127 lies midway
return 'light' # (127 - 255) denotes light image
else:
return 'dark' # (0 - 127) denotes dark image
Refer to these - 参考这些-
Smoothing , Mean , Thresholding 平滑 , 均值 , 阈值
Personally, I would not bother writing any Python , or loading up OpenCV for such a simple operation. 就我个人而言,我不会为这种简单的操作而编写任何Python或加载OpenCV 。 If you absolutely have to use Python, please just disregard this answer and select a different one. 如果您绝对必须使用Python,请忽略此答案,然后选择其他答案。
You can just use ImageMagick at the command-line in your Terminal to get the mean brightness of an image as a percentage, where 100 means "fully white" and 0 means "fully black" , like this: 您可以在终端的命令行中使用ImageMagick来获取图像的平均亮度,以百分比表示,其中100表示“全白” ,0表示“全黑” ,如下所示:
convert someImage.jpg -format "%[fx:int(mean*100)]" info:
Alternatively, you can use libvips
which is less common, but very fast and very lightweight: 另外,您可以使用不太常见的libvips
,但速度非常快而且非常轻巧:
vips avg someImage.png
The vips
answer is on a scale of 0..255 for 8-bit images. 对于8位图像, vips
答案的缩放比例为0..255。
Note that both these methods will work for many image types, from PNG, through GIF, JPEG and TIFF. 请注意,这两种方法都适用于多种图像类型,从PNG到GIF,JPEG和TIFF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.