(笔记三)opencv图像基础操作

强调:本文只为学习记录做笔记
详细可参考opencv官网 :https://docs.opencv.org/4.1.1/d0/d86/tutorial_py_image_arithmetics.html

(1)将cv2的BGR模式改为RGB模式

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: LIFEI
@time: 2023/8/29 10:24 
@file: test3.py
@project: pythonProject
@describe: TODO
@# -------------------------------------------------(one)----------------------------------------------
@# -------------------------------------------------(two)----------------------------------------------
"""
import cv2
from matplotlib import pyplot as plt
import numpy as np

img = cv2.imread(r"D:\data\img.png")
img2 = img
plt.figure(1)
# 将cv2的BGR模式改为RGB模式
img1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.subplot(121), plt.imshow(img, 'gray'), plt.title('BGR')
plt.subplot(122), plt.imshow(img1, 'gray'), plt.title('RGB')
# 必须要有
plt.show()

(笔记三)opencv图像基础操作_第1张图片

(2)获取图像的基础信息并更改图像像元值

(笔记三)opencv图像基础操作_第2张图片

print('shape:', img2.shape)  # 获取图像的大小
print('dtype:', img2.dtype)  # 获取图像的类型
print('chanel:', img2[200, 200])  # 获取图像的某个点的像素值
print(img2.item(200, 200, 0))  # = img[200,200,0]
img2.itemset((200, 200, 0), 100)  # = img[200,200,0]=100
print('modify:', img2.item(200, 200, 0))

(3)拆分图像通道以及组合

(笔记三)opencv图像基础操作_第3张图片

img3 = img
b, g, r = cv2.split(img)  # 拆分bgr通道
img4 = cv2.merge((r, g, b))
img5 = cv2.merge((g, b, r))
img6 = cv2.merge((r, r, b))
plt.figure(2)
plt.subplot(221), plt.imshow(img3), plt.title('BGR')
plt.subplot(222), plt.imshow(img4), plt.title('RGB')
plt.subplot(223), plt.imshow(img5), plt.title('GBR')
plt.subplot(224), plt.imshow(img6), plt.title('RRB')
plt.show()

(4)更改图像的某个区域

(笔记三)opencv图像基础操作_第4张图片

img7 = img1
R = img[100:300, 100:300]
R[:, :, 1:2] = 255
img7[200:400, 200:400] = R
plt.figure(3), plt.imshow(img7), plt.title('modify channels')
plt.show()

(5)更改图像大小以及两个图像进行叠加

(笔记三)opencv图像基础操作_第5张图片

img8 = img1
img9 = cv2.imread(r'D:\data\780.png')
img9 = cv2.cvtColor(img9, cv2.COLOR_BGR2RGB)
x,y,z = img1.shape
img9 = cv2.resize(img9,(y,x))
img8_img9 = cv2.addWeighted(img8, 0.6, img9, 0.4,0)
plt.figure(4)
plt.subplot(131),plt.imshow(img8), plt.title('img1')
plt.subplot(132),plt.imshow(img9), plt.title('img2')
plt.subplot(133),plt.imshow(img8_img9), plt.title('img3')
plt.show()

(6)按位运算

(笔记三)opencv图像基础操作_第6张图片

img2gray = cv2.cvtColor(img9, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 120, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
plt.figure(5)
plt.subplot(131), plt.imshow(img9), plt.title('ori')
plt.subplot(132), plt.imshow(mask, 'gray'), plt.title('gray')
plt.subplot(133), plt.imshow(mask_inv, 'gray'), plt.title('gray_inv')
plt.show()

你可能感兴趣的:(opencv2学习笔记,笔记,opencv)