慕侠2389804
实现PIL.ImageEnhance.Contrast非常简单。您可以在 OpenCV 中模仿(此处:仅对于 BGR 图像,您需要添加对所有可能的颜色类型的支持):import cv2import numpy as npfrom PIL import Image, ImageEnhancedef 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)这是一些测试代码:import cv2from matplotlib import pyplot as pltimport numpy as npfrom PIL import Image, ImageEnhancedef 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()这就是输出:----------------------------------------System information----------------------------------------Platform: Windows-10-10.0.16299-SP0Python: 3.8.5Matplotlib: 3.3.2NumPy: 1.19.3OpenCV: 4.4.0Pillow: 8.0.1----------------------------------------