OpenCV

您所在的位置:网站首页 灰度图转rgb OpenCV

OpenCV

2024-01-13 12:15| 来源: 网络整理| 查看: 265

二值图、灰度图、RGB彩色图 二值图灰度图RGB彩色图8位整型图像浮点数图像通道的分离与合并彩色图像转为灰度图图像二值化完整代码

二值图

二值图:只有 0 和 1 两种取值

灰度图

灰度图:对8位灰度取值,有256种取值, 0表示黑色,1表示白色。 彩色图像转灰度图像公式: g r a y ( x , y ) = 0.299 r ( x , y ) + 0.587 g ( x , y ) + 0.114 b ( x , y ) gray(x,y) = 0.299r(x,y) + 0.587g(x,y) + 0.114b(x,y) gray(x,y)=0.299r(x,y)+0.587g(x,y)+0.114b(x,y)

import numpy as np import matplotlib.pyplot as plt import cv2 as cv def show(img): if img.ndim == 2: plt.imshow(img, cmap='gray') else: plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)) plt.show() A = np.random.randint(0, 256, (2, 4), dtype=np.uint8) show(A)

在这里插入图片描述

RGB彩色图

RGB彩色图:

真彩色:R、G、B通道各有8位取值假彩色:8位表示256种颜色。暂不讨论。 B = np.random.randint(0, 256, (2, 4, 3), dtype=np.uint8) show(B)

在这里插入图片描述

8位整型图像 C = np.uint8([-100, 0, 100, 255, 355, 27]).reshape((2, -1)) print(C) # 8位整型图像,自动转换非uint8为uint8 show(C) # [[156 0 100] # [255 99 27]]

在这里插入图片描述

浮点数图像 A2 = np.float32(A) # 浮点数图像 print(A2) show(A2)

在这里插入图片描述

A2 /= 255 print(A2) show(A2)

在这里插入图片描述

通道的分离与合并

显示原图像

img = cv.imread('dog.jpg') show(img)

在这里插入图片描述 分离通道

b,g,r = cv.split(img) show(b) show(g) show(r)

通道合并

img2 = cv.merge([b,g,r]) show(img2)

在这里插入图片描述

彩色图像转为灰度图 # 彩色图像转换为灰度图 gray1 = 1/3*b + 1/3*g + 1/3 * r show(gray1) gray2 = np.uint8(gray1) # 类型转换方式一 gray3 = gray1.astype(np.uint8) # 类型转换方式二 gray4 = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # 彩色转灰度,上面的转换方式只为介绍原理,主要使用这个api show(gray4)

在这里插入图片描述

图像二值化 # 图像二值化,需先将图像转为灰度图像后,才能二值化 thresh = 125 gray4[gray4 > thresh] = 255 # True部分设置位255 print(gray4) show(gray4) # [[255 255 255 ... 255 255 255] # [255 255 255 ... 255 255 255] # [255 255 255 ... 255 255 255] # ... # [255 255 255 ... 62 61 61] # [255 255 255 ... 63 63 62] # [255 255 255 ... 64 64 64]]

在这里插入图片描述

gray4[gray4 thresh] = 255 # True部分设置位255 print(gray4) show(gray4) gray4[gray4


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3