彩图、灰度图、二值图的转化

import numpy as np
from matplotlib import pyplot as plt
import cv2 as cv

def show(img):
    if img.ndim == 2:
        plt.imshow(img,cmap='gray',vmin=0,vmax=255)
    else:
        plt.imshow(cv.cvtColor(img,cv.COLOR_BGR2RGB))
    plt.show()

if __name__ == '__main__':
    a = np.random.randint(0,256,(2,4),dtype=np.uint8)  #二位灰度图
    # show(a)
    b = np.random.randint(0,256,(2,4,3),dtype=np.uint8)   #彩图
    # print(np.uint8([-1,0,255,300]))

    #通道分离与合并
    img = cv.imread('image/apple.jpg')
    b,g,r = cv.split(img)  #分离
    img2 = cv.merge([b,g,r])   #合并

    #彩图转灰度图
    gray1 = 0.114*b + 0.587*g + 0.299*r   #权值可变
    print(gray1)
    gray2 = gray1.astype(np.uint8)  #将浮点数转为整数
    gray3 = np.uint8(gray1)    #将浮点数转为整数

    #彩图转为灰度图
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)

    #二值化图像(灰度转二值)
    thresh = 125
    print(gray1 > thresh)  #结果为True和False的二维矩阵
    gray1[gray1 > thresh] = 255
    gray1[gray1 <= thresh] = 0
    # show(gray1)

    # 二值化图像(灰度转二值)
    ignore,gray4 = cv.threshold(gray2,125,255,cv.THRESH_BINARY)  #有两个返回值,灰度图为int8型,将大于125的设置成255,小于变0
    # show(gray4)

 

posted @ 2023-01-12 20:25  能吃八碗饭  阅读(202)  评论(0)    收藏  举报