1 回答
TA贡献1719条经验 获得超6个赞
实现PIL.ImageEnhance.Contrast
非常简单。您可以在 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)
这是一些测试代码:
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()
这就是输出:
----------------------------------------
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
----------------------------------------
添加回答
举报