Files
zjsh_yolov11/image_chuantong/gama.py
琉璃月光 df7c0730f5 bushu
2025-10-21 14:11:52 +08:00

53 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/python
# coding:utf-8
import cv2
import numpy as np
# 读取彩色图
img = cv2.imread('2.jpg') # 读取原始图像 (BGR格式)
if img is None:
print("错误:无法读取图像 '1.png',请确认文件存在且路径正确。")
exit()
# 转为RGB进行处理便于归一化等操作
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 归一化到0~1
img_normalized = img_rgb / 255.0
# 定义两个不同的gamma值
gamma1 = 1 / 1.5 # 约等于 0.67,提亮暗部
gamma2 = 1.5 # 压暗亮部
# 伽马校正
img_gamma1 = np.power(img_normalized, gamma1)
img_gamma2 = np.power(img_normalized, gamma2)
# 转回 0~255 并转换为 uint8 类型
img_gamma1 = np.uint8(img_gamma1 * 255)
img_gamma2 = np.uint8(img_gamma2 * 255)
# 转回 BGR 格式以便用 OpenCV 保存OpenCV 默认使用 BGR
img_gamma1_bgr = cv2.cvtColor(img_gamma1, cv2.COLOR_RGB2BGR)
img_gamma2_bgr = cv2.cvtColor(img_gamma2, cv2.COLOR_RGB2BGR)
# 保存图像
cv2.imwrite('original.png', img) # 原始图像
cv2.imwrite('gamma_0.67.png', img_gamma1_bgr) # gamma = 1/1.5 ≈ 0.67
cv2.imwrite('gamma_1.5.png', img_gamma2_bgr) # gamma = 1.5
print("已保存三张图像:")
print(" original.png")
print(" gamma_0.67.png")
print(" gamma_1.5.png")
# 可选显示图像如果在有GUI的环境下运行
show_images = False # 设置为 True 可显示图像
if show_images:
cv2.imshow('Original', img)
cv2.imshow('Gamma = 1/1.5 (~0.67)', img_gamma1_bgr)
cv2.imshow('Gamma = 1.5', img_gamma2_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()