目录
- import cv2
- from matplotlib import pyplot as plt
- import numpy as np
-
- # 加载RGB图片
- img_OpenCV = cv2.imread(r"demo.jpeg")
- print(type(img_OpenCV), img_OpenCV.shape) #
(484, 515, 3) -
- # 分割颜色通道,opencv使用BGR颜色格式
- b, g, r = cv2.split(img_OpenCV)
- # imread()方法返回ndarray对象,因此也可以使用切片分割颜色通道
- B = img_OpenCV[:, :, 0]
- G = img_OpenCV[:, :, 1]
- R = img_OpenCV[:, :, 2]
- print((b == B).all(), (g == G).all(), (r == R).all()) # True True True
-
- # 转换成RGB颜色格式
- img_matplotlib = cv2.merge([r, g, b])
- img_ndarray = img_OpenCV[:, :, ::-1]
- print((img_matplotlib == img_ndarray).all()) # True
-
- # 使用matplotlib可视化图片
- plt.subplot(121)
- plt.imshow(img_OpenCV)
- plt.subplot(122)
- plt.imshow(img_matplotlib)
- # plt.show()
-
- # 使用opencv可视化图片
- cv2.imshow('BGR image', img_OpenCV)
- cv2.imshow('RGB image', img_matplotlib)
- # 拼接图片
- img_connect = np.concatenate((img_OpenCV, img_matplotlib), axis=1)
- cv2.imshow('BGR image-RGB image', img_connect)
-
- cv2.waitKey(0) # 等待键盘动作
- cv2.destroyAllWindows() # 关闭窗口
- import cv2
-
- # 加载灰度图片
- img_OpenCV = cv2.imread(r"demo.png", cv2.IMREAD_GRAYSCALE)
- print(type(img_OpenCV), img_OpenCV.shape) #
(484, 515) - cv2.imshow('BGR image', img_OpenCV)
-
- # 图片切片
- img_split = img_OpenCV[100:200, 250:350]
- cv2.imshow("BGR image", img_split)
-
- cv2.waitKey(0) # 等待键盘动作
- cv2.destroyAllWindows() # 关闭窗口
- """
- @Title: Black And White
- @Time: 2024/3/13
- @Author: Michael Jie
- """
-
- import cv2
-
- # 加载灰度图片
- img_OpenCV = cv2.imread(r"demo.png", cv2.IMREAD_GRAYSCALE)
- print(type(img_OpenCV), img_OpenCV.shape) #
(484, 515) - print(img_OpenCV)
-
- # 二值化图像
- ret, img_binary = cv2.threshold(
- # 图像
- img_OpenCV,
- # 阈值
- thresh=200,
- # 填充色
- maxval=255,
- # 填充类型
- type=cv2.THRESH_BINARY # 小于阈值置0,大于阈值置填充色
- )
- cv2.imshow('BlackAndWhite image', img_binary)
-
- # 自适应阈值
- img_binary1 = cv2.adaptiveThreshold(
- # 图像
- img_OpenCV,
- # 填充色
- maxValue=255,
- # 填充类型
- adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C,
- # 二值化方法,计算阈值
- thresholdType=cv2.THRESH_BINARY,
- # 邻域大小,奇数
- blockSize=11,
- # 从计算的平均值或加权平均值中减去常数
- C=8
- )
- cv2.imshow('BlackAndWhite image1', img_binary1)
-
- cv2.waitKey(0) # 等待键盘动作
- cv2.destroyAllWindows() # 关闭窗口
-
- """
- 阈值类型 小于等于阈值 大于阈值
- THRESH_BINARY 0 maxval
- THRESH_BINARY_INV maxval 0
- THRESH_TRUNC 保持原样 thresh
- THRESH_TOZERO 0 保持原样
- THRESH_TOZERO_INV 保持原样 0
- """
-
- """
- 二值化方法
- ADAPTIVE_THRESH_MEAN_C 邻域的平均值
- ADAPTIVE_THRESH_GAUSSIAN_C 邻域值的加权和
- """