简体   繁体   English

OpenCV 中 PIL 库函数 ImageEnhance.Contrast(image).enhance(param) 的等价物是什么?

[英]What is the equivalent of PIL library function ImageEnhance.Contrast(image).enhance(param) in OpenCV?

I've converted some PIL library function to OpenCV function, but I can't find a substitute of the following function using OpenCV functions.我已经将一些 PIL 库函数转换为 OpenCV 函数,但是我无法使用 OpenCV 函数找到以下函数的替代品。 Here is the PIL library function:这是 PIL 库函数:

img = ImageEnhance.Contrast(image).enhance(param)

The implementation of PIL.ImageEnhance.Contrast is quite simple. PIL.ImageEnhance.Contrast实现非常简单。 You can mimic that in OpenCV (here: only for BGR images, you'd need to add support for all possible color types):您可以在 OpenCV 中模仿(此处:仅对于 BGR 图像,您需要添加对所有可能的颜色类型的支持):

import cv2
import numpy as np
from PIL import Image, ImageEnhance


def cv2_enhance_contrast(img, factor):
    mean = np.uint8(cv2.mean(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))[0])
    img_deg = np.ones_like(img) * mean
    return cv2.addWeighted(img, factor, img_deg, 1-factor, 0.0)

Here's some test code:下面是一些测试代码:

import cv2
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image, ImageEnhance


def cv2_enhance_contrast(img, factor):
    mean = np.uint8(cv2.mean(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))[0])
    img_deg = np.ones_like(img) * mean
    return cv2.addWeighted(img, factor, img_deg, 1-factor, 0.0)


img_pil = Image.open('path/to/your/image.png')
img_pil_enh = ImageEnhance.Contrast(img_pil).enhance(0.25)
img_cv = cv2.imread('path/to/your/image.png')
img_cv_enh = cv2_enhance_contrast(img_cv, 0.25)

plt.figure(figsize=(8, 8))
plt.subplot(2, 2, 1), plt.imshow(img_pil), plt.title('PIL original')
plt.subplot(2, 2, 3), plt.imshow(img_pil_enh), plt.title('PIL enhanced')
plt.subplot(2, 2, 2), plt.imshow(img_cv[:, :, ::-1]), plt.title('OpenCV original')
plt.subplot(2, 2, 4), plt.imshow(img_cv_enh[:, :, ::-1]), plt.title('OpenCV enhanced')
plt.tight_layout(), plt.show()

And that'd be the output:这就是输出:

输出

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
Matplotlib:  3.3.2
NumPy:       1.19.3
OpenCV:      4.4.0
Pillow:      8.0.1
----------------------------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM