In [1]:
def show(img):
# 判断图片的维度
if img.ndim == 2: # 说明是灰度图读取
plt.imshow(img, cmap='gray')
elif img.ndim == 3: # 彩色图片
img2 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.imshow(img2)
else:
print('不知道是什么图!')
return
plt.show()
In [2]:
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
图像基础¶
In [3]:
# 灰度图矩阵
a = np.random.randint(0, 256, (2, 4), dtype=np.uint8)
a
Out[3]:
array([[ 55, 75, 112, 246], [211, 22, 172, 176]], dtype=uint8)
In [4]:
show(a)
In [5]:
# 彩色图矩阵
b = np.random.randint(0, 255, (2, 4, 3), dtype=np.uint8)
b
Out[5]:
array([[[ 1, 43, 92], [ 29, 61, 26], [106, 53, 88], [168, 75, 206]], [[233, 167, 16], [122, 60, 180], [ 12, 213, 249], [203, 117, 250]]], dtype=uint8)
In [6]:
show(b)
In [7]:
# np.uint8([-1, 0, 10, 55, 255]) 这种写法后续会被遗弃,换成下面的写法
np.array([-1, 0, 10, 55, 255, 256]).astype(np.uint8)
Out[7]:
array([255, 0, 10, 55, 255, 0], dtype=uint8)
通道分离和合并¶
In [8]:
img = cv.imread('../pic/2color.png')
print("原图")
show(img)
# 分离通道
b, g, r = cv.split(img)
print("B")
show(b)
print("G")
show(g)
print("R")
show(g)
原图
B
G
R
In [9]:
# 显示图片长 宽 通道数
img.shape
Out[9]:
(772, 581, 3)
In [10]:
b.shape
Out[10]:
(772, 581)
In [11]:
# 合并图片
img2 = cv.merge([b, g, r])
show(img2)
img2 = cv.merge([r, g, b])
show(img2)
彩色图转换成灰度图¶
In [12]:
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
show(img_gray)
把灰度图转换为二值化图像¶
In [13]:
# 函数 cvThreshold 对单通道数组应用固定阈值操作。该函数的典型应用是对灰度图像进行阈值操作得到二值图像
_, img_bin = cv.threshold(img_gray, 125, 255, cv.THRESH_BINARY)
img_bin
Out[13]:
array([[255, 255, 255, ..., 0, 0, 0], [255, 255, 255, ..., 0, 0, 0], [255, 255, 255, ..., 0, 0, 0], ..., [ 0, 0, 0, ..., 255, 255, 255], [ 0, 0, 0, ..., 255, 255, 255], [255, 0, 0, ..., 255, 255, 255]], dtype=uint8)
In [14]:
show(img_bin)
图像的加减乘除¶
In [15]:
img1 = cv.imread('../pic/1png.png', 0)
show(img1)
img2 = cv.imread('../pic/1png_add.png', 0)
show(img2)
In [16]:
# 相加
img_add = cv.add(img1 * 0.5, img2 * 0.5)
show(img_add)
img_add = cv.subtract(img_add, img2 * 0.5)
show(img_add)
img_add = cv.multiply(img1 * 0.5, img2 * 0.5)
show(img_add)
img_add = cv.divide(img1 * 0.5, img2 * 0.5)
show(img_add)
图像像素的线性和非线性变换¶
In [17]:
img = cv.imread("../pic/2color.png", 0)
show(img)
In [18]:
# 线性变换
b = 20
k = 2
img2 = b + k * img.astype(np.int32)
img2 = np.clip(img2, 0, 255)
show(img2)
In [19]:
# cvConvertScaleAbs函数是OpenCV中的函数,使用线性变换转换输入数组元素成8位无符号整型
# void cv::convertScaleAbs(
# cv::InputArray src, // 输入数组
# cv::OutputArray dst, // 输出数组
# double alpha = 1.0, // 乘数因子
# double beta = 0.0 // 偏移量
# );
img3 = cv.convertScaleAbs(img, alpha=2, beta=20)
show(img3)
In [20]:
# 非线性变换
img4 = 10 + np.log(img.astype(np.float32) + 1) / 0.1
show(img4)
In [21]:
img01 = img / 255
img05 = np.power(img01, 0.5) * 255
img15 = np.power(img01, 1.5) * 255
show(np.hstack([img05, img,img15]))
In [ ]: