提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
进行实验2
提示:以下是本篇文章正文内容,下面案例可供参考
二、实验内容
(1) 读入灰度图像,分析其直方图特征,并使用直方图均衡法对图像进行处理;
(2) 采用灰度变换增强图像;
(3) 使用多幅高斯白噪声图像平均去除高斯白噪声;
(4) 使用中值滤波去除噪声;
(5) 分别用 Laplace 算子和 sobel 算子实现图像的锐化增强。
代码如下(示例):
# -*- codeing = utf-8 -*-
# @Time : 2022/4/20
# @File : ShiYan2.py
# @Software: PyCharm
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as Img
import numpy as np
import math
from PIL import Image
#(1)读入灰度图像,提取该图像的灰度直方图。
def show(img):
if img.ndim ==2:
plt.imshow(img,cmap='gray')
else:
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
plt.show()
return
def normalization(data):
data = data/np.sum(data)
return data
def salt(image, prob):
output = np.zeros(image.shape, np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = np.random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
return output
def My1(img):
#采用柱状图绘制
#读取图像转为灰度
src = np.array(img.convert("L"))
plt.show()
colors =[]
#记录每一个灰度值的像素
if not colors:
for i in range(256):
colors.append(np.sum(src == i))
pixels = [i for i in range(256)]
#转变为概率分布
c = normalization(colors)
#减少运算时间
src_for_hist = src.reshape(1,-1).tolist()
show(src)
plt.figure()
plt.bar(pixels,c)
plt.figure()
plt.hist(src_for_hist,bins=255,density=1)
plt.show()
#方法2直接用函数
hist = cv2.calcHist([img],[0],1,[256],[0,256])
def My2(img):
src = np.array(img.convert("L"))
colors = []
#记录每一个灰度值的像素
if not colors:
for i in range(256):
colors.append(np.sum(src == i))
normalizaed_colors = colors/np.sum(colors)
h,w = src.shape
dst = np.zeros_like(src)
for i in range(h):
for j in range(w):
res = 0
for k in range(src[i,j]):
res+=normalizaed_colors[k]
s = 255*res
dst[i][j] = np.round(s)
if i%50==0:
print("finish ",i," line",",total ",h," line")
plt.figure()
plt.imshow(src,cmap ='gray',vmin=0,vmax=255)
plt.axis("off")
plt.figure()
plt.imshow(dst, cmap='gray', vmin=0, vmax=255)
plt.axis("off")
plt.figure()
plt.hist(src.reshape(1,-1).tolist(),bins=255,density=1)
plt.figure()
plt.hist(dst.reshape(1,-1).tolist(),bins=255,density=1)
plt.show()
def My3():
def gamma_trans(image, c=1, gamma=0.5):
normalized_image = image / 255
result = c * np.power(normalized_image, gamma)
return np.float64(result)
src = Img.imread("P2/img_3.jpg")
dst = gamma_trans(src)
plt.figure()
plt.imshow(src, vmin=0, vmax=255)
plt.axis("off")
plt.figure()
plt.imshow(dst, vmin=0, vmax=255)
plt.axis("off")
plt.show()
def My4(img):
src = np.array(img.convert("L"))
plt.figure()
plt.imshow(src, vmin=0, vmax=255)
plt.axis("off")
normalized_img = src /255
noise = np.random.normal(size=normalized_img.shape)*0.1
noised_img = normalized_img+noise
plt.figure()
plt.imshow(noised_img, vmin=0, vmax=255)
plt.axis("off")
dst = np.zeros_like(src,dtype='float64')
noised_img_list = []
for i in range(40):
noise = np.random.normal(size=normalized_img.shape) *0.1
noised_img = normalized_img + noise
noised_img_list.append(noised_img)
dst+=noised_img
dst = dst/40
plt.figure()
plt.imshow(dst, cmap="gray")
plt.axis("off")
_,fig = plt.subplots(5,8,figsize=(12,18))
plt.subplots_adjust(top=0.985,bottom=0.015,right=0.987,hspace=0.0,wspace=0.113)
for i in range(5):
for j in range(8):
fig[i][j].imshow(noised_img_list[i+j],cmap="gray")
fig[i][j].axis("off")
plt.show()
def My5(img):
src = np.array(img.convert("L"))
plt.figure()
plt.imshow(src, cmap="gray")
plt.axis("off")
noise = salt(src, 0.2)
plt.figure()
plt.imshow(noise, cmap="gray")
plt.axis("off")
def median_filter(src_img):
kernel_size = 3
fill = int((kernel_size - 1) / 2)
img = np.pad(src_img, fill, 'constant')
height, width = src_img.shape
arr = np.zeros_like(src_img, dtype="float64")
for i in range(height):
for j in range(width):
corr = img[i:i + kernel_size, j:j + kernel_size]
arr[i, j] = np.median(corr)
return arr
dst = median_filter(noise)
plt.figure()
plt.imshow(dst, cmap="gray")
plt.axis("off")
plt.show()
def My6(img):
src = np.array(img.convert("L"))
plt.figure()
plt.imshow(src, cmap="gray")
plt.axis("off")
def laplace(img, c):
kernel = 3
lap_filter = np.array([[1, 1, 1],
[1, -8, 1],
[1, 1, 1]])
fill = int((kernel - 1) / 2)
padded_img = np.pad(img, fill, 'constant')
height, width = img.shape
arr = np.zeros_like(img, dtype="float64")
for i in range(height):
for j in range(width):
corr = padded_img[i:i + kernel, j:j + kernel]
r = np.sum(np.dot(lap_filter, corr))
arr[i, j] = padded_img[i, j] + c * r
return arr
dst_h = laplace(src, -0.2)
plt.figure()
plt.imshow(dst_h, cmap="gray")
plt.axis("off")
def sobel_h(src, c, kernel=3):
sobel_filter = np.array([[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]])
fill = int((kernel - 1) / 2)
img = np.pad(src, fill, 'constant')
height, width = src.shape
arr = np.zeros_like(src, dtype="float64")
for i in range(height):
for j in range(width):
corr = img[i:i + kernel, j:j + kernel]
R = np.sum(sobel_filter * corr)
arr[i, j] = src[i, j] + c * R
return arr
dst = sobel_h(src, 1)
plt.figure()
plt.imshow(dst, cmap="gray")
plt.axis("off")
def sobel_v(src, c, kernel=3):
sobel_filter = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
fill = int((kernel - 1) / 2)
img = np.pad(src, fill, 'constant')
height, width = src.shape
arr = np.zeros_like(src, dtype="float64")
for i in range(height):
for j in range(width):
corr = img[i:i + kernel, j:j + kernel]
R = np.sum(sobel_filter * corr)
arr[i, j] = src[i, j] + c * R
return arr
dst_v = sobel_v(src, 1)
plt.figure()
plt.imshow(dst_v, cmap="gray")
plt.axis("off")
plt.show()
if __name__ == '__main__':
img = Image.open("P2/img.png")
img1 = Img.imread("P2/img_3.jpg")
# 重设大小
#读入灰度图像,提取该图像的灰度直方图。
#My1(img)
# 直方图均衡化
#My2(img)
#2. 采用灰度变换增强图像;
My3()
#使用多幅高斯白噪声图像平均去除高斯白噪声;
#My4(img)
# 使用中值滤波去除噪声;
#My5(img)
#分别用 Laplace 算子和 sobel 算子实现图像的锐化增强。
#My6(img)
#使用opencv
#My7(img)
(1) 了解图像灰度变换与空间滤波的原理;
(2) 熟悉灰度变换、直方图修正、图像平滑、图像锐化在数字图像增强方面的作用及各自的特点;
(3) 掌握图像增强的灰度变换法、直方图修正法;
(4) 掌握图像平滑、图像锐化的滤波器设计方法;