基于python的opencv项目实战P3

03-图像处理

视频来源b站
准备工作:

#检查并读取图像

import cv2 
import matplotlib.pyplot as plt 
import numpy as np 
get_ipython().run_line_magic('matplotlib','inline') 

img = cv2.imread('lena.jpg')
img_gray = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
cv2.imwrite('lena_gray.png',img_gray)

cv2.imshow('image',img)
cv2.imshow('image_gray',img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像阈值

ret,dst = cv2.threshold(src,thresh,maxval,type)

  • src:输入图,只能是单通道
  • dst:输出图
  • thresh:阈值
  • maxval:当像素值超过了阈值(小于阈值根据type定)所赋予的值
  • type:二值化操作类型:
    • cv2.THRESH_BINARY;超过阈值取最大值,否则为0
    • cv2.THRESH_BINARY_INV;上述反转
    • cv2.THRESH_BINARY_TRUNC;大于阈值部分设为阈值,否则不便
    • cv2.THRESH_TOZERO;大于阈值部分不改变,否则设为0
    • cv2.THRESH_TOZERO_INV.上述反转
#不同阈值操作并展示
ret,thresh1 = cv2.threshold(img_grey,127,255, cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img_grey,127,255, cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img_grey,127,255, cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img_grey,127,255, cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img_grey,127,255, cv2.THRESH_TOZERO_INV)


titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img,thresh1,thresh2,thresh3,thresh4,thresh5]


for i in range(6):
    plt.subplot(2, 3, i + 1), plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

图像平滑操作

img_Noise = cv2.imread('lena_Noise.jpg')
cv2.imshow('img_Noise',img_Noise)
cv2.waitKey(0)
cv2.destroyAllWindows()

#均值滤波,简单的平均卷积操作
blur = cv2.blur(img_Noise,(3,3))

cv2.imshow('blur',blur)
cv2.waitKey(0)
cv2.destroyAllWindows()

#方框滤波,和均值滤波差不多,可以选择归一化
box = cv2.boxFilter(img_Noise,-1,(3,3),normalize=True)

cv2.imshow('box',box)
cv2.waitKey(0)
cv2.destroyAllWindows()

#方框滤波,和均值滤波差不多,不选择归一化容易越界
box = cv2.boxFilter(img_Noise,-1,(3,3),normalize=False)

cv2.imshow('box',box)
cv2.waitKey(0)
cv2.destroyAllWindows()

#高斯滤波
aussian = cv2.GaussianBlur(img_Noise,(5,5),1)

cv2.imshow('aussian',aussian)
cv2.waitKey(0)
cv2.destroyAllWindows()

#中值滤波
median = cv2.medianBlur(img_Noise,5)

cv2.imshow('median',median)
cv2.waitKey(0)
cv2.destroyAllWindows()
#展示所有

res = np.hstack((blur,aussian,median)) #vstack为竖直排列
cv2.imshow('median vs average',res)
cv2.waitKey(0)
cv2.destroyAllWindows()

p.s.
来自https://www.cnblogs.com/vincentcheng/p/9261556.html
引用:
图片-https://www.cnblogs.com/vincentcheng/p/9261556.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值