2019-02-18 10:20:11 qq_34725005 阅读数 113
• ###### matlab基于直方图优化的图像去雾技术

matlab基于直方图优化的图像去雾技术

390 人正在学习 去看看 刘昱显
``````import matplotlib.pyplot as plt
import numpy as np
import cv2

def convert(r):
x = np.zeros([256])
for i in range(r.shape[0]):
for j in range(r.shape[1]):
x[r[i][j]]+=1
x = x/r.size
sum_x = np.zeros([256])
for i,_ in enumerate(x):
sum_x[i] = sum(x[:i])
s = np.empty(r.shape,dtype=np.uint8)
for i in range(r.shape[0]):
for j in range(r.shape[1]):
s[i][j] = 255 * sum_x[r[i][j]]
return s

im_mat = np.asarray(im)

#原直方图
plt.hist(im_mat.reshape([im_mat.size]),256,density=1)
plt.show()

#均衡化直方图
im_converted_mat = convert(im)
plt.hist(im_converted_mat.reshape([im_converted_mat.size]),256,density=1)
plt.show()

#均衡化图
cv2.imshow('original',im)
cv2.imshow('jpg',im_converted_mat)
cv2.waitKey()
``````

2018-04-24 11:40:18 u010936286 阅读数 400
• ###### matlab基于直方图优化的图像去雾技术

matlab基于直方图优化的图像去雾技术

390 人正在学习 去看看 刘昱显

```clear
clc
%%读取图像数据

%%灰度化
Cells_bright_gray=rgb2gray(Cells_bright);
Cells_dark_gray=rgb2gray(Cells_dark);
Cells_low_contrast_gray=rgb2gray(Cells_low_contrast);
Cells_hight_contrast_gray=rgb2gray(Cells_hight_contrast);

%%求直方图
h_bright         =imhist(Cells_bright_gray)/numel(Cells_bright_gray);
h_dark           =imhist(Cells_dark_gray)/numel(Cells_dark_gray);
h_low_contrast   =imhist(Cells_low_contrast_gray)/numel(Cells_low_contrast_gray);
h_hight_contrast =imhist(Cells_hight_contrast_gray)/numel(Cells_hight_contrast_gray);

%%绘制直方图
h=0:255;
figure(1)
subplot(1,2,1)
imshow(Cells_bright)
title('细胞亮')
subplot(1,2,2)
bar(h,h_bright);
title('直方图')
axis([0,255,0,0.1])

figure(2)
subplot(1,2,1)
imshow(Cells_dark_gray)
title('细胞暗')
subplot(1,2,2)
bar(h,h_dark);
title('直方图')
axis([0,255,0,0.1])

figure(3)
subplot(1,2,1)
imshow(Cells_low_contrast_gray)
title('细胞低对比度')
subplot(1,2,2)
bar(h,h_low_contrast);
title('直方图')
axis([0,255,0,0.1])

figure(4)
subplot(1,2,1)
imshow(Cells_hight_contrast_gray)
title('细胞高对比度')
subplot(1,2,2)
bar(h,h_hight_contrast);
title('直方图')
axis([0,255,0,0.1])```

```%%直方图均衡
hist_equilibrium=histeq(Cells_bright_gray);

%%直方图
Image_equilibrium_hist=imhist(hist_equilibrium)/numel(hist_equilibrium);
%%绘制直方图均衡后图像
figure(5)
subplot(1,2,1)
imshow(g)
title('细胞亮直方图均衡后的图片')
subplot(1,2,2)
bar(h,Image_equilibrium_hist);
title('直方图')
axis([0,255,0,0.1])```

```clear
clc
%%读取图像数据

%%灰度化
Mars_gray=rgb2gray(Mars);

%%直方图
h=0:255;
h_Mars=imhist(Mars_gray)/numel(Mars_gray);
figure(1)
subplot(1,2,1)
imshow(Mars_gray)
title('火星灰度图')
subplot(1,2,2)
bar(h,h_Mars);
title('直方图')
axis([0,255,0,1])

%%直方图均衡
hist_equilibrium=histeq(Mars_gray);
Mars_equilibrium_hist=imhist(hist_equilibrium)/numel(hist_equilibrium);
figure(2)
subplot(1,2,1)
imshow(hist_equilibrium)
title('火星直方图均衡')
subplot(1,2,2)
bar(h,Mars_equilibrium_hist);
title('直方图')
axis([0,255,0,1])```

（1）P(r)→P(s)

（2）P(z)→P(s)，P(s)→P(z)

（3）P(r)→P(s)→P(z)

```%%指定直方图分布律
p(1:100)=-16/50/50*(h(1:100)-50).^2+18;
p(101:256)=2;
p=p/sum(p);
figure(3)
plot(h,p);
title('指定的直方图')

%%直方图匹配
hist_matching=histeq(Mars_gray,p);
Mars_matching_hist=imhist(hist_matching)/numel(hist_matching);
figure(4)
subplot(1,2,1)
imshow(hist_matching)
title('火星直方图匹配')
subplot(1,2,2)
bar(h,Mars_matching_hist);
title('直方图')
axis([0,255,0,1])```

```clear
clc
%%读取图像数据

%%灰度化
Tungsten_gray=rgb2gray(Tungsten);

%%直方图
h=0:255;
h_Tungsten=imhist(Tungsten_gray)/numel(Tungsten_gray);
%%绘制直方图
figure(1)
subplot(1,2,1)
imshow(Tungsten_gray)
title('放大约130倍钨丝的SME图像')
subplot(1,2,2)
bar(h,h_Tungsten);
title('直方图')
axis([0,255,0,0.1])

%%全局直方图均衡
hist_equilibrium=histeq(Tungsten_gray);
Tungsten_equilibrium_hist=imhist(hist_equilibrium)/numel(hist_equilibrium);
figure(2)
subplot(1,2,1)
imshow(hist_equilibrium)
title('全局直方图均衡')
subplot(1,2,2)
bar(h,Tungsten_equilibrium_hist);
title('直方图')
axis([0,255,0,1])```

K2>1则表示增强亮区域，若k2<1则表示增强暗区域。

```%%直方图统计
Tungsten_gray=double(Tungsten_gray);    %格式转化，便于后期计算
Tungsten_mean_G =mean(Tungsten_gray(:));  %全局平均值
k0=0.25;
Tungsten_std_G=std(Tungsten_gray(:));   %全局标准差
k2=0.4;
k1=0.02;
E=4.0;
if k1>=k2
disp(['输入错误，k1>k2'])
end

n=3;    %局部均衡邻域范围
st=floor(n/2);           %以像素所在位置为(2,2)为例，其邻域为[1:3,1:3]。
image_extend=wextend('2D','sym',Tungsten_gray,n);%%扩展
Tungsten_result=Tungsten_gray;              %用于得到结果
[row,col]=size(image_extend);              %扩展后的图像大小
for i=1+n:row-n
for j=1+n:col-n
img_temp=image_extend(i-st:i+st,j-st:j+st);   %获取像素(i,j)的邻域
img_temp_mean=mean(img_temp(:));         %求局部均值
img_temp_std=std(img_temp(:));           %求局部标准差
if img_temp_mean<=k0*Tungsten_mean_G && img_temp_std<=k2*Tungsten_std_G &&img_temp_std>=k1*Tungsten_std_G;
Tungsten_result(i-n,j-n)=img_temp(st+1,st+1)*E;  %将该像素增强E倍
end

end
end
Tungsten_result=uint8(Tungsten_result);
Tungsten_result_hist=imhist(Tungsten_result)/numel(Tungsten_result);
figure(3)
subplot(1,2,1)
imshow(Tungsten_result)
title('局部直方图统计增强后的图像')
subplot(1,2,2)
bar(h,Tungsten_result_hist);
title('直方图')
axis([0,255,0,0.1])```

```k0=0.4;
k2=0.4;
k1=0.02;
E=4.0;```

`j=1+n+floor(col/2):col-n`

2019-07-21 23:12:46 u012292754 阅读数 171
• ###### matlab基于直方图优化的图像去雾技术

matlab基于直方图优化的图像去雾技术

390 人正在学习 去看看 刘昱显

# 1 `Image Histtogram`

## 1.1 画直方图

• `HistogramFilter`
``````package demo2.histogram;

import demo2.utils.AbstractImageOptionFilter;

import java.awt.image.BufferedImage;
import java.util.Arrays;

public class HistogramFilter extends AbstractImageOptionFilter {
private int[] histData;

public HistogramFilter() {
histData = new int[256];
}

public int[] getHistData() {
return histData;
}

public void setHistData(int[] histData) {
this.histData = histData;
}

@Override
public BufferedImage process(BufferedImage src) {
int width = src.getWidth();
int height = src.getHeight();
int[] pixels = new int[width * height];
getRGB(src, 0, 0, width, height, pixels);
int index = 0;
Arrays.fill(histData, 0);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
index = row * width + col;
int pixel = pixels[index];
int tr = (pixel >> 16) & 0xff; // red
histData[tr]++;
}
}

return src;
}
}

``````
• `ImagePanel`
``````package demo2.histogram;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImagePanel extends JComponent implements ActionListener {

private BufferedImage image;

private JButton processBtn;

private int[] histdata;

public ImagePanel(BufferedImage image) {
this.image = image;
}

public JButton getButton() {
processBtn = new JButton("按钮");

return processBtn;
}

@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (null != image) {
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
}

if (histdata != null) {
int xstart = image.getWidth() + 50;
int ystart = image.getHeight();

g2d.setPaint(Color.BLACK);
g2d.drawLine(xstart, 0, xstart, ystart); // Y 轴
g2d.drawLine(xstart, ystart, xstart + 256, ystart); // x轴

// find max value
int max = -1;
int min = 0;
for (int i = 0; i < histdata.length; i++) {
max = Math.max(max, histdata[i]);
}

float delta = max - min;
g2d.setPaint(Color.YELLOW);
for (int i = 0; i < histdata.length; i++) {
float v1 = histdata[i] - min;
int value = (int) ((v1 / delta) * 256);
g2d.drawLine(xstart + i + 1, ystart, xstart + i + 1, ystart - value);
}

}

}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == processBtn) {
this.process();
this.repaint();
}
}

public void process() {
HistogramFilter filter = new HistogramFilter();
filter.process(this.image);
histdata = filter.getHistData();

for (int i = 0; i < histdata.length; i++) {
System.out.println("灰度值" + i + ":" + histdata[i]);
}
}

public static void main(String[] args) {
File file = new File("resource/gray.jpg");

try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImagePanel imp = new ImagePanel(image);

JPanel flowPanel = new JPanel();
flowPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

frame.setSize(500, 400);
frame.setTitle("图像显示测试");
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}

}

}

``````

# 2 直方图均衡化

• 均衡化公式
• r: 输入图像的灰度级别
• s: 输出图像的灰度级别

• 直方图数据到均衡化

• `HistgramBalanceFilter`
``````package demo2.histogrambalance;

import demo2.utils.AbstractImageOptionFilter;

import java.awt.image.BufferedImage;
import java.util.Arrays;

public class HistgramBalanceFilter extends AbstractImageOptionFilter {
@Override
public BufferedImage process(BufferedImage src) {
int width = src.getWidth();
int height = src.getHeight();
int[] pixels = new int[width * height];
int[] output = new int[width * height];
getRGB(src, 0, 0, width, height, pixels);
BufferedImage dest = createCompatibleDestImage(src, src.getColorModel());
int index = 0;
double[] histData = new double[256];
Arrays.fill(histData, 0);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
index = row * width + col;
int pixel = pixels[index];
int tr = (pixel >> 16) & 0xff; // red
histData[tr]++;
}
}

// 归一化，变成 0-1 之间的数据
double total = pixels.length;
for(int i=0; i<histData.length; i++) {
histData[i] = histData[i] / total;
}

// setup lookup table
int[] lut = new int[256];
for(int i=0; i<lut.length; i++) {
double sum = 0.0;
for(int j=0; j<=i; j++) {
sum += histData[j];
}
lut[i] = (int)Math.floor(sum * 255 + 0.5);
}

// 直方图均衡化
for(int row=0; row<height; row++) {
for(int col=0; col<width; col++) {
index = row * width + col;
int pixel = pixels[index];
int tr = (pixel >> 16) & 0xff;
output[index] = (0xff << 24 | lut[tr] << 16 | lut[tr] << 8 | lut[tr]);
}
}

setRGB(dest, 0, 0, width, height, output);
return dest;
}
}

``````

2019-09-02 21:16:05 weixin_44225182 阅读数 291
• ###### matlab基于直方图优化的图像去雾技术

matlab基于直方图优化的图像去雾技术

390 人正在学习 去看看 刘昱显

## 图像直方图归一化

``````t=imread('a1.jpg')
subplot(1,2,1),imshow(t),title('原图')
subplot(1,2,2),imhist(t),title('图像直方图')
``````

Imhist

imhist(I,n)
imhist(X,map)
[counts,x] = imhist(I)

`````` t=imread('a1.jpg')
subplot(2,3,1),imshow(t),title('原图')
subplot(2,3,2),imhist(t),title('灰度级数默认：256')
subplot(2,3,3),imhist(t,128),title('灰度级数：128')
subplot(2,3,4),imhist(t,64),title('灰度级数：64')
subplot(2,3,5),imhist(t,32),title('灰度级数：32')
subplot(2,3,6),imhist(t,16),title('灰度级数：16')
``````

n的定义是灰度级数，这里我们可以理解为将0~255分成几份，比如默认为256，就是分成256份，一份是1，所以灰度值每隔1就统计一次；又n为128，则把0-255分成128份，一份为2，灰度值每隔2统计一次，所以从对比图像看，n为128的看起来比n为256的更稀疏。

[counts,x] = imhist(I)这句话的意思是，获取直方图的横坐标和纵坐标，即各个像素级，以及每个像素级上的像素出现的次数，这个有个易错点，就是，counts其实是直方图的纵坐标值，而x才是直方图的横坐标。

``````F=imread('a1.jpg');
I=rgb2gray(F);
subplot(1,3,1),imshow(I),title('原图')
subplot(1,3,2),imhist(I),title('原图的图像直方图')
[count,x]=imhist(I)
% 获取直方图的横坐标和纵坐标，即各个像素级，以及每个像素级上的像素出现的次数 counts:纵坐标 x：横坐标
subplot(1,3,3),stem(x,count),title('根据图像直方图绘制的统计图')
% 通过刚才得到的值，绘制条形图。
``````

``````F=imread('a1.jpg');
I=rgb2gray(F);
[m,n]=size(I)
subplot(1,4,1),imshow(I),title('原图')
subplot(1,4,2),imhist(I),title('原图的图像直方图')
[count,x]=imhist(I)
subplot(1,4,3),stem(x,count),title('根据图像直方图绘制的统计图')
count=count/m/n
% 获取直方图的横坐标和纵坐标，即各个像素级，以及每个像素级上的像素出现的次数 counts:纵坐标 x：横坐标
subplot(1,4,4),stem(x,count),title('图像直方图归一化')
``````

2019-09-03 15:43:01 weixin_44225182 阅读数 770
• ###### matlab基于直方图优化的图像去雾技术

matlab基于直方图优化的图像去雾技术

390 人正在学习 去看看 刘昱显

## 图像直方图均衡化

`````` H= imread('a1.jpg');
if length(size(H))>2
H=rgb2gray(H);
end
subplot(3,2,1);
imshow(H); title('原图');
subplot(3,2,2);
imhist(H); title('原图直方图');
subplot(3,2,3);
subplot(3,2,4);
subplot(3,2,5);
H2=histeq(H);
imshow(H2); title('histeq均衡后图');
subplot(3,2,6);
imhist(H1); title('histeq均衡后直方图');
``````

``````H= imread('a1.jpg');

%判断是否为三通道彩色图片 若是 则将其灰度化
if length(size(H))>2
H=rgb2gray(H);
end

%获取图片的尺寸 便于计算总像素数 即m*n
[m,n]=size(H);

%生成一个一行256列的矩阵
p=zeros(1,256);

% 统计各灰度的像素个数
%find(H==i) 是在图像矩阵里面寻找灰度为i的点坐标
% 因为矩阵是从1开始的 所以为p(i+1)
for i=0:255
p(i+1)=length(find(H==i))/(m*n);
end

subplot(2,2,1);
imshow(H);
title('原图');
subplot(2,2,2);
% 显示原图的直方图
bar(0:255,p,'b');
title('原图直方图');

% 利用循环 累加概率值
s=zeros(1,256);
for i=1:256
for j=1:i
s(i)=p(j)+s(i);
end
end

%对s中的数先乘以255，再取整
a=round(s*255);
b=H;
%更新原图像的灰度
for i=0:255
b(find(H==i))=a(i+1);
end

subplot(2,2,3);
imshow(b)
title('均衡化后图像');
%统计更新后的概率
for i=0:255
GPeq(i+1)=sum(p(find(a==i)));
end
subplot(2,2,4);
bar(0:255,GPeq,'b'); title('均衡化后的直方图');
``````

``````Img= imread('a1.jpg');
if length(size(Img))>2
Img=rgb2gray(Img);
end

%绘制原始图像的直方图
[height,width]=size(Img);
[counts1, x] = imhist(Img,256);
counts2 = counts1/height/width;
figure(1),
subplot(1,2,1),
imshow(Img);title('原始图像');
subplot(1,2,2),
stem(x, counts2); title('原始图像直方图');

%统计每个灰度的像素值累计数目
NumPixel = zeros(1,256);%统计各灰度数目，共256个灰度级
for i = 1:height
for j = 1: width
%对应灰度值像素点数量+1
%NumPixel的下标是从1开始，而图像像素的取值范围是0~255，所以用NumPixel(Img(i,j) + 1)
NumPixel(Img(i,j) + 1) = NumPixel(Img(i,j) + 1) + 1;
end
end

%将频数值算为频率
ProbPixel = zeros(1,256);
for i = 1:256
ProbPixel(i) = NumPixel(i) / (height * width * 1.0);
end

%函数cumsum来计算cdf，并将频率（取值范围是0.0~1.0）映射到0~255的无符号整数
CumuPixel = cumsum(ProbPixel);
CumuPixel = uint8(255 .* CumuPixel + 0.5);

%直方图均衡。赋值语句右端，Img(i,j)被用来作为CumuPixel的索引
for i = 1:height
for j = 1: width
Img(i,j) = CumuPixel(Img(i,j)+1);
end
end

%显示更新后的直方图
figure(2),
subplot(1,2,1),
imshow(Img); title('直方图均衡化图像');
[counts1, x] = imhist(Img,256);
counts2 = counts1/height/width;
subplot(1,2,2),
stem(x, counts2); title('直方图均衡化后图像的直方图');
``````

``````Img= imread('a1.jpg');
OutImg=Img;
%分别提取三通道的信息
R = Img(:,:,1);
G = Img(:,:,2);
B = Img(:,:,3);

%分别对三通道的图片进行均衡化
R = histeq(R, 256);
G = histeq(G, 256);
B = histeq(B, 256);

%最后合成为一张图片
OutImg(:,:,1) = R;
OutImg(:,:,2) = G;
OutImg(:,:,3) = B;

figure,
subplot(1,2,1),
imshow(Img);title('原始图像');
subplot(1,2,2),
imshow(OutImg); title('均衡化后结果');
``````

``````mg= imread('a1.jpg');
hsvImg = rgb2hsv(Img);
V=hsvImg(:,:,3);
[height,width]=size(V);

V = uint8(V*255);
NumPixel = zeros(1,256);
for i = 1:height
for j = 1: width
NumPixel(V(i,j) + 1) = NumPixel(V(i,j) + 1) + 1;
end
end

ProbPixel = zeros(1,256);
for i = 1:256
ProbPixel(i) = NumPixel(i) / (height * width * 1.0);
end

CumuPixel = cumsum(ProbPixel);
CumuPixel = uint8(255 .* CumuPixel + 0.5);

for i = 1:height
for j = 1: width
V(i,j) = CumuPixel(V(i,j)+1);  %注意，这里需要+1，要不然会出问题
end
end

V = im2double(V);
hsvImg(:,:,3) = V;
outputImg = hsv2rgb(hsvImg);
figure,
subplot(1,2,1),
imshow(Img);title('原始图像');
subplot(1,2,2),
imshow(outputImg); title('在HSV空间均衡化后结果');
``````