OpenCV |
您所在的位置:网站首页 › 灰度图转rgb › OpenCV |
二值图、灰度图、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 |