如何获得图像的亮度梯度

How to get luminance gradient of an image

我正在努力通过图像亮度检查来理解图像,我试图通过下面的代码找到图像的亮度

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)

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'

没有你的进一步description/clarification,我假设你想要图像亮度的梯度。所以,首先我们需要亮度图像,然后是梯度。请注意,下面的示例代码根本没有经过测试,它只是给出了如何进行的一般思路。

亮度只是灰度图像的同义词,因此根据您选择的库,您可以:

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 并采用第三通道:

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)

您 link 访问的网站似乎将其与原始网站混合在一起,我猜这可以通过以下方式完成:

fraction = 0.3
mixed = cv2.AddWeighted(im, fraction, grad, 1.0-fraction, ...)