计算机视觉——图像增强

图像增强的定义非常广泛,一般来说,图像增强是有目的地强调图像的整体或局部特性,例如改善图像的颜色、亮度和对比度等,将原来不清晰的图像变得清晰或强调某些感兴趣的特征,扩大图像中不同物体特征之间的差别,抑制不感兴趣的特征,提高图像的视觉效果。传统的图像增强已经被研究了很长时间,现有的方法可大致分为三类,空域方法是直接对像素值进行处理,如直方图均衡,伽马变换;频域方法是在某种变换域内操作,如小波变换;混合域方法是结合空域和频域的一些方法。传统的方法一般比较简单且速度比较快,但是没有考虑到图像中的上下文信息等,所以取得效果不是很好。

 

近年来,卷积神经网络在很多低层次的计算机视觉任务中取得了巨大突破,包括图像超分辨、去模糊、去雾、去噪、图像增强等。对比于传统方法,基于CNN的一些方法极大地改善了图像增强的质量。现有的方法大多是有监督的学习,对于一张原始图像和一张目标图像,学习它们之间的映射关系,来得到增强后的图像。但是这样的数据集比较少,很多都是人为调整的,因此需要自监督或弱监督的方法来解决这一问题。本实验采用经典算法对图像进行增强,并使用深度学习中的神经对抗网络模型对增强效果进行优化。

  • 原始图像存在的问题

图1:原始图像

从图中可以看出,图片整体偏暗,亮度较低,而且对比度较低,图片与效果图像左右颠倒。通过绘制该图片的灰度直方图和累计直方图可以看出,图片中像素点的灰度值都集中在较低的区域。

图2:原始图像灰度直方图和累计直方图

  • 增强方法
  1. 直方图均衡化(HE)

一张图像的对比度可以理解为图像中细节可被肉眼分辨的程度,而图像的均衡化可以增强图像的对比度,可以通过灰度直方图来体现图像的对比度。在直方图中,较灰暗的图像颜色直方图分布往往分布在一个比较小的像素值范围内,而较为清晰图像的颜色直方图在整个像素灰度值范围内分布的比较均匀。因此我们可以得出图像对比度越高,在由灰度/像素个数构成的直角坐标系中横向跨度越大,纵向长度越趋于一致。在横坐标上跨度越长也就说明图像中使用的灰度值越多,也就能够更加清晰的反映图像中每一个细节与它周围的细节直接的差别。

图3:直方图均衡化

从图像的灰度直方图可以看出,图片进行直方图均衡化后,像素点的灰度值范围被拉伸,图像灰度间距被拉开,使灰度分布均匀,从而增大对比度。

但直方图均衡化存在一些缺点:

1.增强效果不易控制,处理的结果总是得到全局均匀化的直方图。

2.均衡化图像的动态范围扩大,但量化级别反而减少了,导致某些图像细节消失。

3.对于直方图存在高峰的图像,经处理后对比度可能过分增强。

从图中可以看出均衡化后的图像填空亮度过高,且填空各部分之间存在不均匀,不平滑的问题。

  1. 对比度受限的自适应直方图均衡化(CLAHE):

为了提高图像的局部对比度,有人提出了AHE,即将图像划分为若干子块,对子块进行HE处理。对于这种处理方式,不难想到,AHE对局部对比度提高过大,会导致图像失真,此外,局部对比度过高还会放大图像中的噪声。

针对以上问题,就提出了对比度受限的自适应直方图均衡化(CLAHE),对子块中得到的直方图进行剪裁,使其幅值低于给定的上限。由于剪裁掉的部分是像素点的数量,因此不能丢掉。所以要将这部分像素点均匀的分布在整个灰度区间上,以保证没有像素点缺失,如下图:

   

图4:对比度受限的自适应直方图均衡化

  1. 直方图规定化

所谓直方图规定化,就是通过一个灰度映像函数,将原灰度直方图改造成所希望的直方图。说的通俗一点就是,原图像的灰度是从0~255的,其分布是随机的,在一些情况下,我们可能需要一些特定的灰度值,比如我们只需要灰度值为0,3,40,240,255 这些值,除此之外的灰度值我们不需要,那么从原图像到我们需要的图像就可以理解成图像的规定化。

在运用均衡化原理基础上,通过建立原始图像和期望图像之间的关系,使原始图像的直方图匹配特定的形状,从而弥补直方图均衡化不具备交互作用的特性。

 

图5:直方图规定化

  1. 其他增强方法

线性变换:在曝光不足或过度的情况下,图像灰度可能会局限在一个很小的范围内。这时就形成一个模糊不清,似乎没有灰度层次的图像,采用线性变换对图像每个像素灰度做线性拉伸,可以有效改善图像视觉效果。原理:y = ax + b。

拉普拉斯变换:使用二阶微分线性算子,与一阶微分相比,二阶微分的边缘定位能力更强,锐化效果更好。使用二阶微分算子的基本方法是定义一种二阶微分的离散形式,然后根据这个形式生成一个滤波模板,与图像卷积。

伽马变换:图像曝光不足或过度时,伽马变换可调节图像的对比度。从而对较暗或较亮的图像进行校正。

原理:y=𝑐𝑥^"γ"

γ > 1: 对较亮的图像进行灰度级压缩

γ < 1: 对较暗的图像进行对比度增强,加强图像细节

 

 

图6:其他增强方法

  1. 滤波

图像滤波,即在尽量保留图像细节特征的条件下对目标图像的噪声进行抑制,是图像预处理中不可缺少的操作,其处理效果的好坏将直接影响到后续图像处理和分析的有效性和可靠性。图像滤波不能损坏图像特征及边缘,且图像视觉效果应当更好。

均值滤波:图像处理中常用的手段,从频率域观点来看均值滤波是一种低通滤波器,高频信号将会去掉。均值滤波可以帮助消除图像尖锐噪声,实现图像平滑,模糊等功能。理想的均值滤波是用每个像素和它周围像素计算出来的平均值替换图像中每个像素。

中值滤波:一种非线性的信号处理方法,所以它是一种非线性滤波器,也是一种统计排序滤波器。它将每一像素点的灰度值设置为该点某邻域窗口内的所有像素点灰度值的中值。

中值滤波对孤立的噪声像素即椒盐噪声、脉冲噪声具有良好的滤波效果,可以保持图像的边缘特性,不会使图像产生显著的模糊。中值滤波是把数字图像或数字序列中一点的值用该点的一个邻域中各点值的中值代替,让周围的像素值接近真实值,从而消除孤立的噪声点。

    高斯滤波(也可以说“高斯模糊”)其实就是一种线性平滑滤波,适用于消除高斯噪声,广泛应用于图像处理的减噪过程。简单来说就是整个图像某个像素点的值与周围像素点的值挂钩,是原图像某一像素点的值其实是其本省和周围像素点值的加权平均过程。整个图像相较于原图像会看起来较为模糊,原图像上的某些噪声点在经过周围像素点加权求和后会被剔除掉。

 

 

图7:滤波结果

  1. 锐化及翻转

图像锐化是补偿图像的轮廓,增强图像的边缘及灰度跳变的部分,使图像变得清晰,分为空间域处理和频域处理两类。图像锐化是为了突出图像上地物的边缘、轮廓,或某些线性目标要素的特征。这种滤波方法提高了地物边缘与周围像元之间的反差,因此也被称为边缘增强。

翻转使用opencv中的cv2.flip(src, flipCode[, dst])函数,可直接实现图片绕中心左右翻转。其中src为要操作的图像,flipCode的取值为1,0,-1时,对应的效果分别为水平翻转、垂直翻转、垂直水平翻转。

 

 

图8:锐化和翻转

  1. 生成对抗网络增强

生成对抗网络(GAN)由生成器和判别器组成,生成器负责生成样本,判别器负责判断生成器生成的样本是否为真。生成器要尽可能迷惑判别器,而判别器要尽可能区分生成器生成的样本和真实样本。

DeOldify是一种技术,以彩色和恢复旧的黑白图像,甚至电影片段。它使用了一种名为NoGAN的新型GAN训练方法,用来解决在使用由一个鉴别器和一个生成器组成的正常对抗性网络架构进行训练时出现的主要问题。

 

 

图9:生成对抗网络增强

  • 界面及功能

 

 

图10:程序可视化界面

    1.程序可以选择图片并展示增强后的效果

2.程序点击相应的按钮可以查看直方图、累计直方图、均衡化后的直方图以及对比观不同增强和滤波后的效果图像。

3.可以展示过程中每个步骤的结果,如下图

 

 

图11:增强过程效果展示

4.其他图片效果展示

   

 

    

图12:其他图片效果展示

    图像增强是数字图像处理领域的一个重要分支,通过对图像的亮度、对比度、锐度等进行处理,改善图像的视觉效果、提高图像质量,使图像更符合人眼视觉感受。在进行图像增强时,需要根据图像的特点选择不同的算法和方法,比如直方图均衡化、伽马变换、均值滤波等。

在实践中,我发现图像增强的效果很大程度上取决于调节参数的准确性和技巧。有些算法会引入一些噪声,导致图像变得更加模糊或失真,这时需要通过调整参数或使用其他算法进行修正。同时,不同的图像需要采用不同的增强方法,因此需要根据实际情况进行选择。

另外,我认为图像增强的效果并不是越明显越好,因为过度增强会导致图像失真、噪声增加等问题,甚至会对后续的图像处理和分析造成影响。因此,在进行图像增强时,需要权衡好增强效果和图像质量,选择合适的方法和参数进行处理,以达到更好的效果。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys

import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5.QtGui import QPixmap, QImage, QFont
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QComboBox, QLabel, QPlainTextEdit
from PyQt5.uic.properties import QtGui

_author_ = '张起凡'
# 对数变换
def log(image):
    image_log = np.uint8(np.log(np.array(image) + 1))
    cv2.normalize(image_log, image_log, 0, 255, cv2.NORM_MINMAX)
    # 转换成8bit图像显示
    cv2.convertScaleAbs(image_log, image_log)
    cv2.imencode('.jpg', image_log)[1].tofile("images_output/对数变换.jpg")
    return image_log

def laplacian(image):
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
    image_lap = cv2.filter2D(image, cv2.CV_8UC3, kernel)
    # cv2.imwrite('th1.jpg', image_lap)
    cv2.imencode('.jpg', image_lap)[1].tofile("images_output/拉普拉斯变换.jpg")
    # cv2.imencode('.jpg', image_lap)[1].tofile("process/lps.jpg")
    return image_lap
# 伽马变换
def gamma(image):
    fgamma = 1
    image_gamma = np.uint8(np.power((np.array(image) / 255.0), fgamma) * 255.0)
    cv2.normalize(image_gamma, image_gamma, 0, 255, cv2.NORM_MINMAX)
    cv2.convertScaleAbs(image_gamma, image_gamma)
    cv2.imencode('.jpg', image_gamma)[1].tofile("images_output/伽马变换.jpg")
    cv2.imencode('.jpg', image_gamma)[1].tofile("process/gama.jpg")
    return image_gamma

# 线性变换
def line(image):
    a = 1.2
    # 线性变换 定义float类型
    O = float(a) * image
    # 数据截取 如果大于255 取 255
    O[0 > 255] = 255
    # 数据类型的转换
    O = np.round(O)
    O = O.astype(np.uint8)
    cv2.imencode('.jpg', O)[1].tofile("images_output/线性变换.jpg")
    return O

def bianhuan_describe(img):
    img_lp=laplacian(img)
    img_gama=gamma(img)
    img_line=line(img)
    plt.figure(figsize=(15, 10))

    plt.subplot(221)
    plt.imshow(img, plt.cm.gray)
    plt.title("直方图归一化后")
    plt.axis('off')

    plt.subplot(222)
    plt.imshow(img_line, plt.cm.gray)
    plt.title("线性变换")
    plt.axis('off')

    plt.subplot(223)
    plt.imshow(img_lp, plt.cm.gray)
    plt.title("拉普拉斯变换")
    plt.axis('off')

    plt.subplot(224)
    plt.imshow(img_gama, plt.cm.gray)
    plt.title("伽马变换")
    plt.axis('off')
    plt.savefig("process/far_enhance.jpg")
    plt.savefig("images_output/进一步增强.jpg")
    plt.show()


def mean_filter(noise_img):  # 均值滤波
    result = cv2.blur(noise_img, (2, 2))
    cv2.imencode('.jpg', result)[1].tofile("images_output/均值滤波后.jpg")
    cv2.imencode('.jpg', result)[1].tofile("process/mean_filter.jpg")
    return result
def box_filter(noise_img): # 方框滤波
    result=cv2.boxFilter(noise_img,-1,(15,15),normalize=True)
    cv2.imencode('.jpg', result)[1].tofile("images_output/方框滤波后.jpg")
    return result
def median_filter(noise_img): # 中值滤波
    result = cv2.medianBlur(noise_img, 5)
    cv2.imencode('.jpg', result)[1].tofile("images_output/中值滤波后.jpg")

    return result

def gaussian_filter(noise_img): # 高斯滤波
    gaussian_blurred = cv2.GaussianBlur(noise_img, (15, 15), 0)
    cv2.imencode('.jpg', gaussian_blurred)[1].tofile("images_output/高斯滤波后.jpg")
    return result

def bilateral_filter(noise_img): # 双边滤波
    bilateral_blurred = cv2.bilateralFilter(noise_img, d=10, sigmaColor=30, sigmaSpace=50)
    cv2.imencode('.jpg', bilateral_blurred)[1].tofile("images_output/双边滤波后.jpg")
    return result

def filter_describe(img):
    mean_filter_img=mean_filter(img)
    median_filter_img=median_filter(img)
    gaussian_filter_img=gaussian_filter(img)
    plt.figure(figsize=(15, 10))

    plt.subplot(221)
    plt.imshow(img, plt.cm.gray)
    plt.title("伽马增强")
    plt.axis('off')

    plt.subplot(222)
    plt.imshow(mean_filter_img, plt.cm.gray)
    plt.title("均值滤波")
    plt.axis('off')

    plt.subplot(223)
    plt.imshow(median_filter_img, plt.cm.gray)
    plt.title("中值滤波")
    plt.axis('off')

    plt.subplot(224)
    plt.imshow(gaussian_filter_img, plt.cm.gray)
    plt.title("高斯滤波")
    plt.axis('off')
    plt.savefig("images_output/滤波后.jpg")
    plt.savefig("process/filter_describe.jpg")
    plt.show()

def total_describe():
    ori=cv2.imread("images/image.jpg")
    ori = cv2.cvtColor(ori, cv2.COLOR_BGR2RGB)

    mid_calcGrayHist=cv2.imread("process/mid_calcGrayHist.jpg")
    mid_calcGrayHist = cv2.cvtColor(mid_calcGrayHist, cv2.COLOR_BGR2RGB)
    Histogram_normalization = cv2.imread("process/Histogram_normalization.jpg")
    Histogram_normalization = cv2.cvtColor(Histogram_normalization, cv2.COLOR_BGR2RGB)
    gama = cv2.imread("process/gama.jpg")
    gama = cv2.cvtColor(gama, cv2.COLOR_BGR2RGB)
    mean_filter = cv2.imread("process/mean_filter.jpg")
    mean_filter = cv2.cvtColor(mean_filter, cv2.COLOR_BGR2RGB)
    lps_ruihua = cv2.imread("process/lps_ruihua.jpg")
    lps_ruihua = cv2.cvtColor(lps_ruihua, cv2.COLOR_BGR2RGB)
    result = cv2.imread("process/result.jpg")
    result = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
    better = cv2.imread("images_output/better.jpg")
    better = cv2.cvtColor(better, cv2.COLOR_BGR2RGB)
    plt.figure(figsize=(15, 10))

    plt.subplot(331)
    plt.imshow(ori, plt.cm.gray)
    plt.title("原图")
    plt.axis('off')

    plt.subplot(332)
    plt.imshow(mid_calcGrayHist, plt.cm.gray)
    plt.title("直方图均衡化")
    plt.axis('off')

    plt.subplot(333)
    plt.imshow(Histogram_normalization, plt.cm.gray)
    plt.title("直方图规定化")
    plt.axis('off')

    plt.subplot(334)
    plt.imshow(gama, plt.cm.gray)
    plt.title("伽马增强")
    plt.axis('off')

    plt.subplot(335)
    plt.imshow(mean_filter, plt.cm.gray)
    plt.title("均值滤波")
    plt.axis('off')

    plt.subplot(336)
    plt.imshow(lps_ruihua, plt.cm.gray)
    plt.title("拉普拉斯锐化")
    plt.axis('off')

    plt.subplot(337)
    plt.imshow(result, plt.cm.gray)
    plt.title("结果")
    plt.axis('off')

    plt.subplot(338)
    plt.imshow(better,plt.cm.gray)
    plt.title("对抗网络着色")
    plt.axis('off')
    plt.savefig("process/total.jpg")
    plt.show()


def salt(img, n):
    #椒盐去燥
    for k in range(n):
        i = int(np.random.random() * img.shape[1])
        j = int(np.random.random() * img.shape[0])
        if img.ndim == 2:
            img[j, i] = 255
        elif img.ndim == 3:
            img[j, i, 0] = 255
            img[j, i, 1] = 255
            img[j, i, 2] = 255
        print("去燥完成")
        return img
def calcGrayHist(image): # 计算灰度直方图
    rows, clos = image.shape
    # 创建一个矩阵用于存储灰度值
    grahHist = np.zeros([256], np.uint64)
    print('这是初始化矩阵')
    print(grahHist)
    for r in range(rows):
        for c in range(clos):
            # 通过图像矩阵的遍历来将灰度值信息放入我们定义的矩阵中
            grahHist[image[r][c]] += 1
    print('这是赋值后的矩阵')
    print(grahHist)

    # 计算累加直方图
    x = image.shape[0]
    y = image.shape[1]
    ret = np.zeros(256)
    for r in range(x):
        for c in range(y):
            # 通过图像矩阵的遍历来将灰度值信息放入我们定义的矩阵中
            ret[image[r][c]] += 1
    # for i in range(x):
    #     for j in range(y):
    #         k = grayfig.getpixel((i,j))
    #         ret[k] = ret[k]+1
    for k in range(1, 256):
        ret[k] = ret[k] + ret[k - 1]  # 累加
    for k in range(256):
        ret[k] = ret[k] / (x * y)
    # 画图
    plt.figure(figsize=(25, 10))
    plt.subplot(121)
    x_range = range(256)
    plt.plot(x_range, grahHist, '-', linewidth=3, c='blue')
    # 设置坐标轴的范围
    y_maxValue = np.max(grahHist)
    plt.axis([0, 255, 0, y_maxValue])
    # 设置标签
    plt.yticks(fontproperties='Times New Roman', size=20, weight='bold')  # 设置大小及加粗
    plt.xticks(fontproperties='Times New Roman', size=20, weight='bold')
    plt.title("直方图")
    plt.xlabel('gray Level')
    plt.ylabel("number of pixels")

    plt.subplot(122)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title("累计直方图")
    plt.bar(range(256), ret, color='blue')
    # 显示灰度直方图
    plt.savefig('process/accumulate_img.jpg')
    plt.savefig('images_output/灰度直方图.jpg')
    plt.show()

def mid_calcGrayHist(image): # 灰度直方图均衡化
    equ = cv2.equalizeHist(image)
    plt.figure(figsize=(15, 10))

    plt.subplot(221)
    plt.imshow(image, plt.cm.gray)
    plt.axis('off')

    plt.subplot(222)
    plt.hist(image.ravel(), 256)

    plt.subplot(223)
    plt.imshow(equ, plt.cm.gray)
    plt.axis('off')

    plt.subplot(224)
    plt.hist(equ.ravel(), 256)

    plt.savefig("images_output/直方图均衡化后.jpg")
    plt.savefig("process/fair_img.jpg")
    cv2.imencode('.jpg', equ)[1].tofile("images_output/均衡化后.jpg")
    cv2.imencode('.jpg', equ)[1].tofile("process/mid_calcGrayHist.jpg")
    return equ
    # cv2.namedWindow("W1")
    # cv2.imshow("W1", img3)
    # cv2.waitKey(delay=0)
def histogram_sum(grayfig):#绘制累计直方图
    x = grayfig.shape[0]
    y = grayfig.shape[1]
    ret = np.zeros(256)
    for r in range(x):
        for c in range(y):
            # 通过图像矩阵的遍历来将灰度值信息放入我们定义的矩阵中
            ret[grayfig[r][c]] += 1
    # for i in range(x):
    #     for j in range(y):
    #         k = grayfig.getpixel((i,j))
    #         ret[k] = ret[k]+1
    for k in range(1,256):
        ret[k] = ret[k]+ret[k-1]#累加
    for k in range(256):
        ret[k] = ret[k]/(x*y)
    plt.figure()
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title("累计直方图")
    plt.bar(range(256), ret,color='blue')
    plt.savefig("images_output/累计直方图.jpg")
    plt.show()


def get_map(Hist):
    # 计算概率分布Pr
    sum_Hist = sum(Hist)
    Pr = Hist / sum_Hist
    # 计算累计概率Sk
    Sk = []
    temp_sum = 0
    for n in Pr:
        temp_sum = temp_sum + n
        Sk.append(temp_sum)
    Sk = np.array(Sk)
    # 计算映射关系img_map
    img_map = []
    for m in range(256):
        temp_map = int(255 * Sk[m] + 0.5)
        img_map.append(temp_map)
    img_map = np.array(img_map)
    return img_map


def get_off_map(map_):  # 计算反向映射,寻找最小期望
    map_2 = list(map_)
    off_map = []
    temp_pre = 0  # 如果循环开始就找不到映射时,默认映射为0
    for n in range(256):
        try:
            temp1 = map_2.index(n)
            temp_pre = temp1
        except BaseException:
            temp1 = temp_pre  # 找不到映射关系时,近似取向前最近的有效映射值
        off_map.append(temp1)
    off_map = np.array(off_map)
    return off_map


def get_infer_map(infer_img):
    infer_Hist_b = cv2.calcHist([infer_img], [0], None, [256], [0, 255])
    infer_Hist_g = cv2.calcHist([infer_img], [1], None, [256], [0, 255])
    infer_Hist_r = cv2.calcHist([infer_img], [2], None, [256], [0, 255])
    infer_b_map = get_map(infer_Hist_b)
    infer_g_map = get_map(infer_Hist_g)
    infer_r_map = get_map(infer_Hist_r)
    infer_b_off_map = get_off_map(infer_b_map)
    infer_g_off_map = get_off_map(infer_g_map)
    infer_r_off_map = get_off_map(infer_r_map)
    return [infer_b_off_map, infer_g_off_map, infer_r_off_map]


def get_finalmap(org_map, infer_off_map):  # 计算原始图像到最终输出图像的映射关系
    org_map = list(org_map)
    infer_off_map = list(infer_off_map)
    final_map = []
    for n in range(256):
        temp1 = org_map[n]
        temp2 = infer_off_map[temp1]
        final_map.append(temp2)
    final_map = np.array(final_map)
    return final_map


def get_newimg(img_org, org2infer_maps):
    w, h, _ = img_org.shape
    b, g, r = cv2.split(img_org)
    for i in range(w):
        for j in range(h):
            temp1 = b[i, j]
            b[i, j] = org2infer_maps[0][temp1]
    for i in range(w):
        for j in range(h):
            temp1 = g[i, j]
            g[i, j] = org2infer_maps[1][temp1]
    for i in range(w):
        for j in range(h):
            temp1 = r[i, j]
            r[i, j] = org2infer_maps[2][temp1]
    newimg = cv2.merge([b, g, r])
    return newimg


def get_new_img(img_org, infer_map):
    org_Hist_b = cv2.calcHist([img_org], [0], None, [256], [0, 255])
    org_Hist_g = cv2.calcHist([img_org], [1], None, [256], [0, 255])
    org_Hist_r = cv2.calcHist([img_org], [2], None, [256], [0, 255])
    org_b_map = get_map(org_Hist_b)
    org_g_map = get_map(org_Hist_g)
    org_r_map = get_map(org_Hist_r)
    org2infer_map_b = get_finalmap(org_b_map, infer_map[0])
    org2infer_map_g = get_finalmap(org_g_map, infer_map[1])
    org2infer_map_r = get_finalmap(org_r_map, infer_map[2])
    return get_newimg(img_org, [org2infer_map_b, org2infer_map_g, org2infer_map_r])

def zh_ch(string):
    return string.encode("gbk").decode('UTF-8', errors='ignore')
class Qt_Window(QMainWindow):
    def __init__(self):
        super().__init__()

    def init_ui(self):
        self.path = ("images/")
        self.path2 = ("images_output/")
        self.path3 = ("process/")
        self.img_list = os.listdir(self.path)

        self.window = QMainWindow()
        self.window.resize(1850, 880)
        self.window.move(35, 60)
        self.window.setWindowTitle('图像增强')
        self.add_Button = QPushButton('添加图片', self.window)
        self.add_Button.resize(180, 40)
        self.add_Button.move(350, 30)
        self.comboBox = QComboBox(self.window)
        self.comboBox.resize(250, 40)
        self.comboBox.move(800,30)
        self.comboBox.addItems([self.img_list[i] for i in range(len(self.img_list))])

        self.detect_image = QLabel(self.window)
        self.add_Button.clicked.connect(self.show_img)
        self.detect_image.resize(400, 300)
        self.detect_image.move(50, 200)
        self.result_image = QLabel(self.window)
        self.result_image.resize(400, 300)
        self.result_image.move(500, 200)
        self.add_Button.clicked.connect(self.show_result_img)

        self.final_image = QLabel(self.window)
        self.final_image.resize(400, 300)
        self.final_image.move(950, 200)
        self.add_Button.clicked.connect(self.show_final_img)

        self.better_image = QLabel(self.window)
        self.better_image.resize(400, 300)
        self.better_image.move(1400, 200)
        self.add_Button.clicked.connect(self.show_better_img)

        # 标签
        self.orign = QPlainTextEdit(self.window)
        self.orign.setReadOnly(True)
        self.orign.setPlaceholderText("原始图像")
        self.orign.setFont(QFont("宋体", 13))
        self.orign.resize(120, 40)
        self.orign.move(190, 120)

        self.result = QPlainTextEdit(self.window)
        self.result.setReadOnly(True)
        self.result.setPlaceholderText("结果图像")
        self.result.setFont(QFont("宋体", 13))
        self.result.resize(120, 40)
        self.result.move(640, 120)

        self.standard = QPlainTextEdit(self.window)
        self.standard.setReadOnly(True)
        self.standard.setPlaceholderText("标准图像")
        self.standard.setFont(QFont("宋体", 13))
        self.standard.resize(120, 40)
        self.standard.move(1090, 120)

        self.better_img = QPlainTextEdit(self.window)
        self.better_img.setReadOnly(True)
        self.better_img.setPlaceholderText("优化图像")
        self.better_img.setFont(QFont("宋体", 13))
        self.better_img.resize(120, 40)
        self.better_img.move(1540, 120)

        # 直方图均衡化显示
        self.accumulate_Button = QPushButton('累计直方图', self.window)
        self.accumulate_Button.resize(180, 40)
        self.accumulate_Button.move(200, 700)
        self.accumulate_Button.clicked.connect(self.show_accumulate_img)


        self.fair_Button = QPushButton('直方图均衡化', self.window)
        self.fair_Button.resize(180, 40)
        self.fair_Button.move(500, 700)
        self.fair_Button.clicked.connect(self.show_fair_img)

        # 其他增强方法
        self.other_enhance_Button = QPushButton('其他增强方法', self.window)
        self.other_enhance_Button.resize(180, 40)
        self.other_enhance_Button.move(800, 700)
        self.other_enhance_Button.clicked.connect(self.show_other_methods)

        # 其他增强方法
        self.filtering_Button = QPushButton('图像滤波', self.window)
        self.filtering_Button.resize(180, 40)
        self.filtering_Button.move(1100, 700)
        self.filtering_Button.clicked.connect(self.show_filter)

        # 增强过程
        self.filtering_Button = QPushButton('增强过程', self.window)
        self.filtering_Button.resize(180, 40)
        self.filtering_Button.move(1400, 700)
        self.filtering_Button.clicked.connect(self.show_total)


        self.window.show()


    def show_img(self):
        img = self.comboBox.currentText()
        pix = QPixmap(self.path + "\\" + img)
        self.detect_image.setPixmap(pix)
        self.detect_image.setScaledContents(True)
        # lable = img.split(".")[0]
        # self.number_lable.setText(lable)

    def show_result_img(self):
        img=self.comboBox.currentText()

        # height, width, bytesPerComponent = result.shape
        # bytesPerLine = 3 * width
        # cv2.cvtColor(result, cv2.COLOR_BGR2RGB, result)
        # QImg = QImage(result.data, width, height, bytesPerLine, QImage.Format_RGB888)
        # pixmap = QPixmap.fromImage(QImg)

        pix=QPixmap(self.path2+'result.jpg')
        self.result_image.setPixmap(pix)
        self.result_image.setScaledContents(True)

    def show_final_img(self):
        img = self.comboBox.currentText()
        pix = QPixmap(self.path2 + "\\" + "final.jpg")
        self.final_image.setPixmap(pix)
        self.final_image.setScaledContents(True)

    def show_better_img(self):
        img = self.comboBox.currentText()
        pix = QPixmap(self.path2 + "\\" + "better.jpg")
        self.better_image.setPixmap(pix)
        self.better_image.setScaledContents(True)

    def show_fair_img(self):
        img_input = cv2.imread("process/fair_img.jpg")
        cv2.imshow('Histogram equalization',img_input)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    def show_accumulate_img(self): # 显示累计直方图

        img_input = cv2.imread("process/accumulate_img.jpg")
        cv2.namedWindow("Cumulative Histogram", 0);
        cv2.resizeWindow("Cumulative Histogram", 1800, 720);
        cv2.imshow('Cumulative Histogram',img_input)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    def show_other_methods(self):
        img_input = cv2.imread("process/far_enhance.jpg")
        cv2.imshow('othen methods',img_input)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    def show_filter(self):
        img_input = cv2.imread("process/filter_describe.jpg")
        cv2.imshow('filter',img_input)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    def show_total(self):
        img_input = cv2.imread("process/total.jpg")
        cv2.imshow('total',img_input)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


if __name__ == "__main__":
    img_input = cv2.imread("images/image.jpg")

    gray_img = cv2.cvtColor(img_input, cv2.COLOR_BGR2GRAY)
    cv2.imencode('.jpg', gray_img)[1].tofile("images_output/灰度图.jpg")
    salt_gray = salt(gray_img, 3)
    plt.imshow(salt_gray, cmap="gray")
    plt.show()
    cv2.imencode('.jpg', salt_gray)[1].tofile("images_output/椒盐去噪.jpg")
    # mean_filter(img_input)
    # median_filter(img_input)
    # box_filter(img_input)
    # gaussian_filter(img_input)
    # bilateral_filter(img_input)
    calcGrayHist(gray_img)
    result=mid_calcGrayHist(gray_img)
    print(gray_img.shape)
    # histogram_sum(gray_img) # 累计直方图
    clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(2, 2))  # 自适应直方图均衡化
    cll = clahe.apply(gray_img)
    # res = np.hstack((gray_img, result, cll))
    cv2.imencode('.jpg', cll)[1].tofile("images_output/自适应均衡化后.jpg")
    infer_img_path = 'images_output/final.jpg'  # 基准图像
    infer_img = cv2.imread(infer_img_path)
    infer_map = get_infer_map(infer_img)
    img_org = cv2.imread("process/mid_calcGrayHist.jpg")
    # bianhuan_describe(img_org)
    # gama_img = gamma(img_org)
    new_img = get_new_img(img_org, infer_map)  # 根据映射关系获得新的图像
    cv2.imencode('.jpg', new_img)[1].tofile("images_output/直方图规定化后.jpg")
    cv2.imencode('.jpg', new_img)[1].tofile("process/Histogram_normalization.jpg")

    bianhuan_describe(new_img)
    gama_img = gamma(new_img)


    # filter_img=cv2.imread("process/Histogram_normalization.jpg")
    filter_describe(gama_img)

    mean_img=mean_filter(gama_img)




    # # 拉普拉斯算子锐化
    # kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)  # 定义拉普拉斯算子
    # dst = cv2.filter2D(mean_img, -1, kernel=kernel)  # 调用opencv图像锐化函数
    dst=laplacian(mean_img)
    cv2.imencode('.jpg', dst)[1].tofile("images_output/图像锐化后.jpg")
    cv2.imencode('.jpg', dst)[1].tofile("process/lps_ruihua.jpg")

    img_result = cv2.flip(dst, 1)  # 水平翻转
    cv2.imencode('.jpg', img_result)[1].tofile("images_output/result.jpg")
    cv2.imencode('.jpg', img_result)[1].tofile("process/result.jpg")
    total_describe()




    # 图形用户界面
    app = QApplication([])
    s = Qt_Window()
    s.init_ui()
    app.exec_()
    # print(img_input)

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
冠状动脉OCT图像增强是指通过使用生成对抗网络(GAN)来提高冠状动脉光学相干断层扫描(OCT)图像的对比度和清晰度。这种增强可以帮助医生更准确地诊断和评估冠状动脉疾病。在研究中,Wolterink等人使用GAN来减少图像模糊,通过学习少量成对训练样本的纹理信息,有效地提高了冠状动脉OCT图像的清晰度。他们的方法可以增强图像的对比度,同时保持图像的细节和结构。这种增强技术有助于医生更好地观察和分析冠状动脉OCT图像,从而提高冠状动脉疾病的诊断准确性和治疗效果。\[1\] #### 引用[.reference_title] - *1* *3* [[Style Transfer]——GANs for Medical Image Analysis](https://blog.csdn.net/qq_37151108/article/details/108208917)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [【AI视野·今日CV 计算机视觉论文速览 第166期】Mon, 28 Oct 2019](https://blog.csdn.net/u014636245/article/details/102790591)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

九磅十五便士°

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

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

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

打赏作者

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

抵扣说明:

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

余额充值