我正在努力通过图像亮度检查来理解图像,并尝试通过下面的代码找到图像的亮度
def brightness( im_file ):
im = Image.open(im_file)
stat = ImageStat.Stat(im)
r,g,b = stat.rms
return math.sqrt(0.241*(r**2) + 0.691*(g**2) + 0.068*(b**2))
想了解如何获得整个图像,计算每个像素或一组像素的亮度,类似于 photo-forensics - Luminance Gradient 中实现的内容
实现错误
import cv2
import numpy as np
im = cv2.imread('image.jpeg')
lum = cv2.imread('image.jpeg',cv2.IMREAD_GRAYSCALE)
gradX = cv2.Sobel(lum,cv2.CV_64F,1,0,ksize=5)
gradY = cv2.Sobel(lum,cv2.CV_64F,0,1,ksize=5)
grad = np.sqrt(gradX**2 + gradY**2)
fraction = 0.3
mixed = cv2.addWeighted(im, fraction, grad, 1.0-fraction,0)
block 引用>cv2.error: OpenCV(3.4.2) /io/opencv/modules/core/src/arithm.cpp:659: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'arithm_op'
最佳答案
如果没有您的进一步描述/澄清,我假设您想要图像亮度的梯度。因此,首先我们需要亮度图像,然后是梯度。请注意,下面的示例代码根本没有经过测试,它只是给出了如何继续的总体思路。
亮度只是灰度图像的同义词,因此根据您选择的库,您可以执行以下操作:
from PIL import Image
lum = Image.open('image.png').convert('L') # PIL method
或者:
import cv2
lum = cv2.imread('image.png',cv2.IMREAD_GRAYSCALE) # OpenCV method
您也可以转换为 HSV 并采用第三个 channel :
im = Image.open(f).convert('HSV') # PIL method
H, S, lum = im.split()
或者:
im = cv2.imread('image.png') # OpenCV method
lum = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)[...,2]
现在你想要它的梯度,所以可以是 Sobel 或 Scharr:
# Calculate gradient in x-direction
gradX = cv2.Sobel(... 0,1, ...)
# And y-direction
gradY = cv2.Sobel(... 1,0, ...)
# And get combined gradient
grad = np.sqrt(gradX**2 + gradY**2)
看起来您链接到的网站将其与原始网站混合在一起,我猜这可以通过以下方式完成:
fraction = 0.3
mixed = cv2.AddWeighted(im, fraction, grad, 1.0-fraction, ...)
关于python - 如何获取图像的亮度梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59280375/