OpenCV-图像基础处理

目录

[1 彩色(RGB)图像](#1 彩色(RGB)图像)

[2 灰度图像](#2 灰度图像)

[3 黑白图像](#3 黑白图像)


1 彩色(RGB)图像

  • 使用cv2.imread()函数加载RGB图像;
  • 使用cv2.split()函数分割颜色通道;
  • 将BGR颜色格式转换成RGB颜色格式;
  • 使用matplotlib或cv2.imshow()函数可视化图像。
python 复制代码
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)  # <class 'numpy.ndarray'> (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()  # 关闭窗口

2 灰度图像

  • 使用cv2.imread()函数加载灰度图像;
  • 图像切片。
python 复制代码
import cv2

# 加载灰度图片
img_OpenCV = cv2.imread(r"demo.png", cv2.IMREAD_GRAYSCALE)
print(type(img_OpenCV), img_OpenCV.shape)  # <class 'numpy.ndarray'> (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()  # 关闭窗口

3 黑白图像

  • 将灰度图像转换成黑白图像;
  • 使用cv2.threshold()函数二值化图像;
  • 使用cv2.adaptiveThreshold()函数二值化图像。
python 复制代码
"""
@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)  # <class 'numpy.ndarray'> (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  邻域值的加权和
"""
相关推荐
c_lb7288几秒前
零基础选策略工具,先分清三件事
人工智能·python
夜雪一千2 分钟前
Python如何使用XPath定位没有特征的元素?无id、无class通用定位技巧
开发语言·python
流浪00119 分钟前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·python
鸿芯微控科技24 分钟前
MFC关断后还有流量怎么办?零流量、阀门泄漏、压差与Python分析
c++·python·mfc·质量流量控制器·关断泄漏·零流量测试
点云-激光雷达-Slam-三维牙齿3 小时前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐63 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
从零开始学习人工智能10 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
卷无止境11 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131411 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教11 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi