图像增强实现

传统图像增强的一些方法

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

def random_crop():
    img = cv2.imread('1.jpg')
    img = cv2.resize(img, (240,240), interpolation=cv2.INTER_AREA)

    upper_x = random.randint(0,8)
    dowm_x =upper_x+224
    upper_y = random.randint(0,8)
    dowm_y = upper_y+224
    img2 = img[upper_x:dowm_x,upper_y:dowm_y]
    cv2.imshow('img',img)
    cv2.imshow('img2',img2)
    cv2.waitKey(0)
#random_crop()


def randomHueSaturationValue( hue_shift_limit=(-2,8),sat_shift_limit=(-5,50),val_shift_limit=(0,1.5)):
    img_org = cv2.imread('1.jpg')
    img = cv2.cvtColor(img_org, cv2.COLOR_BGR2HSV)
    h, s ,v = img[:,:,0],img[:,:,1],img[:,:,2]
    hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])

     # h= v + val_sh = h + hue_shift

    sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])
    s = s + sat_shift

    val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])
    
    
    img[:,:,0],img[:,:,1],img[:,:,2] = h, s ,v
    image = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)

    cv2.imshow('img_org',img_org)
    cv2.imshow('image',image)
    cv2.waitKey(0)
#randomHueSaturationValue()

def img_show(org_image,enhance_image):
    org_image_cv2 = cv2.cvtColor(np.asarray(org_image),cv2.COLOR_RGB2BGR)
    enhance_image_cv2 = cv2.cvtColor(np.asarray(enhance_image),cv2.COLOR_RGB2BGR)
    org_image_cv2 = cv2.resize(org_image_cv2, (800,600), interpolation=cv2.INTER_AREA)
    enhance_image_cv2 = cv2.resize(enhance_image_cv2, (800,600), interpolation=cv2.INTER_AREA)
    cv2.imshow('Enhanced image',np.hstack([org_image_cv2,enhance_image_cv2]))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced image')

def image_enhance_color(org_image):
    # #1、调整图像的饱和度
    random_factor = np.random.uniform(0.9,1.3)  # 随机因子
    random_factor = 1.5
    color_image = ImageEnhance.Color(org_image).enhance(random_factor)
    img_show(org_image,color_image)
    return color_image
def image_enhance_brightness(org_image):
    # # 2、调整图像的亮度
    random_factor = np.random.uniform(0.9,1.2)  # 随机因子
    random_factor = 1.5
    brightness_image = ImageEnhance.Brightness(org_image).enhance(random_factor)
    img_show(org_image,brightness_image)
    return brightness_image
def image_enhance_contrast(org_image):
    # 3、调整图像对比度
    random_factor = np.random.uniform(0.9,1.3)  # 随机因子
    random_factor = 1.5
    contrast_image = ImageEnhance.Contrast(org_image).enhance(random_factor)
    img_show(org_image,contrast_image)
    return contrast_image
def image_enhance_sharpness(org_image):
    # 4、调整图像锐度
    random_factor = np.random.uniform(-3,3)  # 随机因子
    #print(random_factor)
    random_factor = 9
    sharpness_image=ImageEnhance.Sharpness(org_image).enhance(random_factor)
    return sharpness_image
def image_enhance():
    org_image = Image.open('2.jpg')
    enhance_image = image_enhance_color(org_image)
    img_show(org_image,enhance_image)
    enhance_image = image_enhance_brightness(org_image)
    img_show(org_image,enhance_image)
    enhance_image = image_enhance_contrast(org_image)
    img_show(org_image,enhance_image)
    enhance_image = image_enhance_sharpness(org_image)
    img_show(org_image,enhance_image)
#image_enhance()

def histogram_equalization1(img):
    # 转为灰度图,进行直方图均衡化
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    enhanced_gray = cv2.equalizeHist(gray)
    cv2.imshow('Enhanced Gray Image',cv2.resize(np.hstack([gray,enhanced_gray]), (1600,600), interpolation=cv2.INTER_AREA))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced Gray Image')
    return enhanced_gray
def histogram_equalization2(img):
    # 直接对 RBG 图像进行直方图均衡化,对每个通道进行均衡化
    (B, G, R) = cv2.split(img)
    B = cv2.equalizeHist(B)
    G = cv2.equalizeHist(G)
    R = cv2.equalizeHist(R)
    enhanced_img = cv2.merge([B,G,R])
    cv2.imshow('Enhanced Color Image',cv2.resize(np.hstack([img,enhanced_img]), (1600,600), interpolation=cv2.INTER_AREA))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced Color Image')
    return enhanced_img
def histogram_equalization3(img):
    # 将图像由 RBG 空间转为 YCrCb 空间,对Y通道进行均衡化
    YCrCb = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB)
    (Y, Cr, Cb) = cv2.split(YCrCb)
    Y = cv2.equalizeHist(Y)
    enhanced_YCrCb = cv2.cvtColor(cv2.merge([Y, Cr, Cb]), cv2.COLOR_YCR_CB2BGR) 
    cv2.imshow('Enhanced YCrCb Image',cv2.resize(np.hstack([img,enhanced_YCrCb]), (1600,600), interpolation=cv2.INTER_AREA))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced YCrCb Image')
    return enhanced_YCrCb
def histogram_equalization4(img):
    # 直接对 RBG 图像进行自适应局部直方图均衡化,对每个通道进行均衡化
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) # create a CLAHE object (Arguments are optional).
    (B, G, R) = cv2.split(img)
    R, G, B = clahe.apply(R), clahe.apply(G), clahe.apply(B)
    enhanced_img = cv2.merge([B,G,R])
    cv2.imshow('Enhanced Color Image',cv2.resize(np.hstack([img,enhanced_img]), (1600,600), interpolation=cv2.INTER_AREA))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced Color Image')
    return enhanced_img
def histogram_equalization5(img):
    # 灰度世界算法(Gray World Algorithm)
    # 取三通道的平均值作为灰度值
    avgB = np.average(img[:, :, 0])  
    avgG = np.average(img[:, :, 1])  
    avgR = np.average(img[:, :, 2])  
    avg = (avgB + avgG + avgR) / 3
    result = np.zeros(img.shape,dtype=np.uint8)
    result[:, :, 0] = np.minimum(img[:, :, 0] * (avg / avgB), 255)
    result[:, :, 1] = np.minimum(img[:, :, 1] * (avg / avgG), 255)
    result[:, :, 2] = np.minimum(img[:, :, 2] * (avg / avgR), 255)
    cv2.imshow('Enhanced Image Gray World Algorithm',cv2.resize(np.hstack([img,result]), (1600,600), interpolation=cv2.INTER_AREA))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced Image Gray World Algorithm')
    return result
def histogram_equalization6(img):
    # 自动白平衡(Automatic White Balance,AWB)
    # 将图像由 RBG 空间转为 LAB 空间
    result = cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
    avg_a = np.average(result[:, :, 1])
    avg_b = np.average(result[:, :, 2])
    for x in range(result.shape[0]):
        for y in range(result.shape[1]):
            l, a, b = result[x, y, :]
            l*=100/255.0
            result[x,y,1] = a - (avg_a-128)*(1/100.0)*1.1
            result[x,y,2] = a - (avg_b-128)*(1/100.0)*1.1
    result = cv2.cvtColor(result,cv2.COLOR_LAB2BGR)
    cv2.imshow('Enhanced Image Automatic White Balance',cv2.resize(np.hstack([img,result]), (1600,600), interpolation=cv2.INTER_AREA))
    cv2.waitKey(0)
    cv2.destroyWindow('Enhanced Image Automatic White Balance')
    return result
def histogram_equalization():
    img = cv2.imread('1.jpg')
    histogram_equalization1(img)
    histogram_equalization2(img)
    histogram_equalization3(img)
    histogram_equalization4(img)
    histogram_equalization5(img)
    histogram_equalization6(img)
#histogram_equalization()

#自动色彩均衡(Automatic Color Equalization,ACE)
def stretchImage(data, s=0.005, bins = 2000):    #线性拉伸,去掉最大最小0.5%的像素值,然后线性拉伸至[0,1]
    ht = np.histogram(data, bins);
    d = np.cumsum(ht[0])/float(data.size)
    lmin = 0; lmax=bins-1
    while lmin<bins:
        if d[lmin]>=s:
            break
        lmin+=1
    while lmax>=0:
        if d[lmax]<=1-s:
            break
        lmax-=1
    return np.clip((data-ht[1][lmin])/(ht[1][lmax]-ht[1][lmin]), 0,1)
g_para = {
      }
def getPara(radius = 5):                        #根据半径计算权重参数矩阵
    global g_para
    m = g_para.get(radius, None)
    if m is not None:
        return m
    size = radius*2+1
    m = np.zeros((size, size))
    for h in range(-radius, radius+1):
        for w in range(-radius, radius+1):
            if h==0 and w==0:
                continue
            m[radius+h, radius+w] = 1.0/math.sqrt(h**2+w**2)
    m /= m.sum()
    g_para[radius] = m
    return m
def zmIce(I, ratio=4, radius=300):                     #常规的ACE实现
    para = getPara(radius)
    height,width = I.shape
    #zh,zw = [0]*radius + range(height) + [height-1]*radius, [0]*radius + range(width)  + [width -1]*radius
    zh,zw = [0]*radius + [x for x in range(height)] + [height-1]*radius, [0]*radius + [x for x in range(width)] + [width -1]*radius
    Z = I[np.ix_(zh, zw)]
    res = np.zeros(I.shape)
    for h in range(radius*2+1):
        for w in range(radius*2+1):
            if para[h][w] == 0:
                continue
            res += (para[h][w] * np.clip((I-Z[h:h+height, w:w+width])*ratio, -1, 1))
    return res
def zmIceFast(I, ratio, radius):                #单通道ACE快速增强实现
    height, width = I.shape[:2]
    if min(height, width) <=2:
        return np.zeros(I.shape)+0.5
    #print(((width+1)/2, (height+1)/2))
    Rs = cv2.resize(I, (int((width+1)/2), int((height+1)/2)))
    Rf = zmIceFast(Rs, ratio, radius)             #递归调用
    Rf = cv2.resize(Rf, (width, height))
    Rs = cv2.resize(Rs, (width, height))
    return Rf+zmIce(I,ratio, radius)-zmIce(Rs,ratio,radius)    
def zmIceColor(I, ratio=4, radius=3):               #rgb三通道分别增强,ratio是对比度增强因子,radius是卷积模板半径
    res = np.zeros(I.shape)
    for k in range(3):
        res[:,:,k] = stretchImage(zmIceFast(I[:,:,k], ratio, radius))
    return res
def ace():
    img = cv2.imread('2.jpg')
    result = zmIceColor(img/255.0)*255
    result = result.astype(np.uint8)
    #cv2.imshow('Enhanced Image',np.hstack([img,result]))
    cv2.imshow('org Image',img)
    cv2.imshow('Enhanced Image',result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
#ace()

ai增强

https://github.com/xinntao/Real-ESRGAN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绯虹剑心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值