python改變單通道圖片的畫素值

weixin_44939146發表於2020-11-03

這段程式碼用於多類分割處理掩碼圖片,在深度學習中,如果有三類分割,需要將標籤設定為0,1,2

#改變圖片畫素值164-1;255-2;
from PIL import Image
import cv2
import os
# img = cv2.imread("F:/AI/glaucoma_set/gla_img_120_Chall/Annotation-Training400/Disc_Cup_Fovea_Illustration/g0001.jpg")
# img = cv2.imread("F:/AI/glaucoma_set/gla_img_120_Chall/Annotation-Training400/Disc_Cup_Masks/Non-Glaucoma_512/n0001.bmp",cv2.IMREAD_UNCHANGED)  # 讀取系統的內照片

def change_pixel(img):
    width = img.shape[0]  # 長度
    height = img.shape[1]  # 寬度
    for i in range(0, width):  # 遍歷所有長度的點
        for j in range(0, height):  # 遍歷所有寬度的點
            if (img[i, j] == 164):
                img[i, j] = 1
            elif (img[i, j] == 255):
                img[i, j] = 2
            else:
                img[i, j] = 0
    return img
if __name__ =="__main__":
    filePath = 'F:/AI/glaucoma_set/gla_img_120_Chall/Annotation-Training400/Disc_Cup_Masks/Glaucoma_512/'
    savePath = 'F:/AI/glaucoma_set/gla_img_120_Chall/Annotation-Training400/Disc_Cup_Masks/Glaucoma_512_012/'
    name = os.listdir(filePath)
    for i in name:
        image_path = os.path.join(filePath,i)
        image_save_Path = os.path.join(savePath,i)
        image = cv2.imread(image_path, cv2.IMREAD_ANYCOLOR)
        img = change_pixel(image)
        cv2.imwrite(image_save_Path, img)

原始512*512單通道圖片畫素值有三個:0,164,255用上述程式碼處理後的圖片,512*512;圖片有三個畫素值:0,1,2

相關文章