图像处理 亮度、CLAHE处理、MSRCR

图像亮度提取

import cv2
import numpy as np
img=cv2.imread('demo.jpg')
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
brightness=np.mean(img_gray)

图像亮度调整

res = np.uint8(np.clip((2 * img + 20), 0, 255))

CLAHE处理

img_clahe = np.zeros_like(img)                              
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) 
for i in range(3):                                          
    img_clahe[:, :, i] = clahe.apply(img[:, :, i])          

MSRCR处理

# -*- coding: utf-8 -*-
import os
import cv2
import numpy as np

def retinex_scales_distribution(max_scale, nscales):
    scales = []
    scale_step = max_scale / nscales
    for s in range(nscales):
        scales.append(scale_step * s + 2.0)
    return scales


def CR(im_ori, im_log, alpha=128., gain=1., offset=0.):
    im_cr = im_log * gain * (
            np.log(alpha * (im_ori + 1.0)) - np.log(np.sum(im_ori, axis=2) + 3.0)[:, :, np.newaxis]) + offset
    return im_cr


def MSRCR(image_path, max_scale, nscales, dynamic=2.0, do_CR=True):
    im_ori = np.float32(image_path[:, :, (2, 1, 0)])
    scales = retinex_scales_distribution(max_scale, nscales)
    im_blur = np.zeros([len(scales), im_ori.shape[0], im_ori.shape[1], im_ori.shape[2]])
    im_mlog = np.zeros([len(scales), im_ori.shape[0], im_ori.shape[1], im_ori.shape[2]])
    for channel in range(3):
        for s, scale in enumerate(scales):
            # If sigma==0, it will be automatically calculated based on scale
            im_blur[s, :, :, channel] = cv2.GaussianBlur(im_ori[:, :, channel], (0, 0), scale)
            im_mlog[s, :, :, channel] = np.log(im_ori[:, :, channel] + 1.) - np.log(im_blur[s, :, :, channel] + 1.)

    im_retinex = np.mean(im_mlog, 0)
    if do_CR:
        im_retinex = CR(im_ori, im_retinex)

    im_rtx_mean = np.mean(im_retinex)
    im_rtx_std = np.std(im_retinex)
    im_rtx_min = im_rtx_mean - dynamic * im_rtx_std
    im_rtx_max = im_rtx_mean + dynamic * im_rtx_std

    im_rtx_range = im_rtx_max - im_rtx_min
    im_out = np.uint8(np.clip((im_retinex - im_rtx_min) / im_rtx_range * 255.0, 0, 255))
    return im_out

if __name__ == '__main__':    
    s=300 #300
    n=3   #3
    d=2   #2
    no_cr=True
    imglist='demo.txt'
    outdir='results'
    f=open(imglist,'r')                      
    lines=f.readlines()                          
    if not os.path.exists(outdir):           
        os.makedirs(outdir)                  
    for line in lines:                       
        imgpath=line.strip().split(' ')[0]                         
        imgdir,imgname=os.path.split(imgpath)
        print('imgpath',imgpath)       
        im=cv2.imread(imgpath)
        if im is None:
            print('img is None!',imgpath)
        h,w,c=im.shape
        #im_size=cv2.resize(im,(int(w/4),int(h/4)))
        im_out = MSRCR(im, s, n, d, not no_cr)
        output=os.path.join(outdir,imgname)
        cv2.imwrite(output, im_out[:, :, (2, 1, 0)])

你可能感兴趣的:(data,图像处理,计算机视觉,opencv)