图像处理基础篇

import cv2
import matplotlib.pyplot as plt
import numpy as np
from PIL.ImageChops import constant

import Cv.Data


# img = cv2.imread("./cat.jpg")  # 读取图像
# img2 = cv2.imread("./cat.jpg", cv2.IMREAD_GRAYSCALE)  # 灰色图像处理
#
# cv2.imshow("cat", img2)  # 展示图像
# cv2.waitKey(0) # 图像消失时间

#
# vc = cv2.VideoCapture("./test.mp4")  # 读取视频
# if vc.isOpened():  # 判断视频打开是否正确
#     open, framc = vc.read()  # 正确  open = True; framc为每一帧图片
# else:
#     open = False
#
# while open:  # 读取成功,则执行以下操作
#     rct, framc = vc.read()  # 继续读取
#     if framc is None:  # 若为空,则返回
#         break
#     if rct == True:  # 处理图片
#         gray = cv2.cvtColor(framc, cv2.COLOR_BGR2GRAY)  # 灰度
#         cv2.imshow('result', gray)  # 展示
#         if cv2.waitKey(100) & 0xFF == 27:
#             break
# cv2.release()
# cv2.destroyAllWindows()

def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# #  截取部分图像数据
# img = cv2.imread('cat.jpg')
# cat = img[0:50, 0:200]  # 按坐标截取图像
# cv_show('cat', cat)


img = cv2.imread('cat.jpg')
b, g, r = cv2.split(img)  # 颜色通道提取

# print(b, g, r)

# 颜色通道合并
img = cv2.merge((b, g, r))  # 颜色通道的还原
# print(img.shape)

# 只保留R通道
# cur_img = img.copy()
# cur_img[:, :, 0] = 0      # 取所有的G通道赋值0
# cur_img[:, :, 1] = 0      # 取所有的B通道赋值为0
# cv_show('R', cur_img)     # 只留R通道,其他相同

# 边界填充
# top_size, bottom_size, left_size, right_size = (50, 50, 50, 50)  # 设置填充范围
# # copyMakeBorder(图片,上下左右size,图像类型)
# replicate = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REPLICATE)
# reflect = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT)
# reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT_101)
# wrap = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_WRAP)
# constant = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_CONSTANT, value=0)
# BORDER_REPLICATE:复制法,也就是复制最边缘像素。
# BORDER_REFLECT:反射法,对感兴趣的图像中的像素在两边进行复制例如:fedcba|abcdefgh|hgfedcb
# BORDER_REFLECT_101:反射法,也就是以最边缘像素为轴,对称,gfedcb|abcdefgh|gfedcba
# BORDER_WRAP:外包装法cdefgh|abcdefgh|abcdefg
# BORDER_CONSTANT:常量法,常数值填充。


# plt.subplot(231), plt.imshow(img, 'gray'), plt.title('ORIGINAL')
# plt.subplot(232), plt.imshow(replicate, 'gray'), plt.title('REPLICATE')
# plt.subplot(233), plt.imshow(reflect, 'gray'), plt.title('REFLECT')
# plt.subplot(234), plt.imshow(reflect101, 'gray'), plt.title('REFLECT_101')
# plt.subplot(235), plt.imshow(wrap, 'gray'), plt.title('WRAP')
# plt.subplot(236), plt.imshow(constant, 'gray'), plt.title('CONSTANT')

# plt.show()

img_cat = cv2.imread('cat.jpg')
img_dog = cv2.imread('dog.jpg')
# img_cat2 = img_cat + 10
# img_cat[:5, :, 0]
# img_cat2[:5, :, 0]
# (img_cat + img_cat2)[:5, :, 0]
# img_cat_dog = cv2.add(img_cat, img_cat2)[:5, :, 0]
# print(img_cat_dog)

# img_cat + img_dog
print(img_cat.shape)
img_dog = cv2.resize(img_dog, (500, 414))
print(img_dog.shape)
# res = cv2.addWeighted(img_cat, 0.4, img_dog, 0.6, 0)
# res = cv2.resize(img, (0, 0), fx=4, fy=4)  # 扩大四倍
res = cv2.resize(img, (0, 0), fx=1, fy=3)  # x不变, y扩大3倍
cv2.imshow('res', res)
cv2.waitKey(0)

import cv2  # opencv读取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt  # Matplotlib是RGB

img = cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(img_gray.shape)

# cv2.imshow("img_gray", img_gray)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# HSV
# H - 色调(主波长)。
# S - 饱和度(纯度/颜色的阴影)。
# V值(强度)

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# cv2.imshow("hsv", hsv)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 图像阈值
# ret, dst = cv2.threshold(src, thresh, maxval, type)
# src: 输入图,只能输入单通道图像,通常来说为灰度图
#
# dst: 输出图
#
# thresh: 阈值
#
# maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
#
# type:二值化操作的类型,包含以下5种类型: cv2.THRESH_BINARY; cv2.THRESH_BINARY_INV; cv2.THRESH_TRUNC;
# cv2.THRESH_TOZERO;cv2.THRESH_TOZERO_INV
#
# cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
#
# cv2.THRESH_BINARY_INV THRESH_BINARY的反转
#
# cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
#
# cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
#
# cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转

ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 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 = cv2.imread('lenaNoise.png')

# cv2.imshow('img', img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 均值滤波
# 简单的平均卷积操作,取周围3*3个数取平均值,通常取单数3,5,7等
blur = cv2.blur(img, (3, 3))
# 方框滤波
# 基本和均值一样,可以选择归一化(归一化则跟均值差距不大)
box = cv2.boxFilter(img, -1, (3, 3), normalize=True)
# 方框滤波,非归一化,出现越界则直接赋值为255
box = cv2.boxFilter(img, -1, (3, 3), normalize=False)
# 高斯滤波
# 高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视与中间值更接近的。
aussian = cv2.GaussianBlur(img, (5, 5), 1)
# 中值滤波
# 排列5*5个数据,取中间位置的值,效果最佳
median = cv2.medianBlur(img, 5)  # 中值滤波
# 展示所有的
res = np.hstack((blur, aussian, median))
# cv2.imshow('blur', blur)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


# 腐蚀操作
img = cv2.imread('dige.png')
# cv2.imshow('image', img)
# cv2.waitKey(0)
kernel = np.ones((3, 3), np.uint8)
# iterations 腐蚀次数   kernel 腐蚀宽度
erosion = cv2.erode(img, kernel, iterations=1)

pie = cv2.imread('pie.png')

kernel = np.ones((30, 30), np.uint8)
erosion_1 = cv2.erode(pie, kernel, iterations=1)
erosion_2 = cv2.erode(pie, kernel, iterations=2)
erosion_3 = cv2.erode(pie, kernel, iterations=3)

res = np.hstack((erosion_1, erosion_2, erosion_3))
# cv2.imshow('res', res)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 膨胀操作,它通常与腐蚀操作一起使用减少图像干扰
img = cv2.imread('dige.png')
kernel = np.ones((3, 3), np.uint8)
dige_erosion = cv2.erode(img, kernel, iterations=1)

dige_dilate = cv2.dilate(dige_erosion, kernel, iterations=1)
pie = cv2.imread('pie.png')

kernel = np.ones((30, 30), np.uint8)
dilate_1 = cv2.dilate(pie, kernel, iterations=1)
dilate_2 = cv2.dilate(pie, kernel, iterations=2)
dilate_3 = cv2.dilate(pie, kernel, iterations=3)
res = np.hstack((dilate_1, dilate_2, dilate_3))
# cv2.imshow('res', res)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 开运算和闭运算
# 开:先腐蚀,再膨胀
img = cv2.imread('dige.png')

kernel = np.ones((5, 5), np.uint8)

# cv2.MORPH_OPEN表示开
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

# cv2.imshow('opening', opening)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 闭:先膨胀,再腐蚀
img = cv2.imread('dige.png')

kernel = np.ones((5, 5), np.uint8)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)

# cv2.imshow('closing', closing)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 梯度运算  先膨胀,再腐蚀,用膨胀减去腐蚀   cv2.MORPH_GRADIENT
pie = cv2.imread('pie.png')
kernel = np.ones((7,7),np.uint8)
dilate = cv2.dilate(pie, kernel, iterations=5)
erosion = cv2.erode(pie, kernel, iterations=5)

res = np.hstack((dilate, erosion))

gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel)

# cv2.imshow('gradient', gradient)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 礼帽和黑帽
# 礼帽:用原始输入减去开运算的输入  cv2.MORPH_TOPHAT
img = cv2.imread('dige.png')
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
# cv2.imshow('tophat', tophat)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 黑帽:闭运算减去原始输入  cv2.MORPH_BLACKHAT
img = cv2.imread('dige.png')
blackhat  = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)
# cv2.imshow('blackhat ', blackhat )
# cv2.waitKey(0)
# cv2.destroyAllWindows()

def cv_show(img,name):
    cv2.imshow(name,img)
    cv2.waitKey()
    cv2.destroyAllWindows()

# 梯度处理
# 图像梯度-Sobel算子,不建议直接运算,因为会模糊
# dst = cv2.Sobel(src, ddepth, dx, dy, ksize)
    # ddepth:图像的深度
    # dx和dy分别表示水平和竖直方向
    # ksize是Sobel算子的大小
img = cv2.imread('pie.png',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx) # 白到黑是正数,黑到白就是负数了,所有的负数会被截断成0,所以要取绝对值
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
# cv_show(sobelxy,'sobelxy')

img = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
img = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
# cv_show(sobelxy,'sobelxy')

# Scharr算子(处理元素更多) && laplacian算子对比(不建议单独使用)
img = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy =  cv2.addWeighted(sobelx,0.5,sobely,0.5,0)

scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy =  cv2.addWeighted(scharrx,0.5,scharry,0.5,0)

laplacian = cv2.Laplacian(img,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)

res = np.hstack((sobelxy,scharrxy,laplacian))
# cv_show(res,'res')


# 边缘处理
img=cv2.imread("lena.jpg",cv2.IMREAD_GRAYSCALE)

v1=cv2.Canny(img,80,150)
v2=cv2.Canny(img,50,100)

res = np.hstack((v1,v2))

img=cv2.imread("car.png",cv2.IMREAD_GRAYSCALE)

v1=cv2.Canny(img,120,250)
v2=cv2.Canny(img,50,100)

res = np.hstack((v1,v2))
cv_show(res,'res')

你可能感兴趣的:(学习笔记记录,图像处理,opencv,计算机视觉)