cv2

文章目录

    • 1、支持中文名称
    • 2、通道数转换
    • 3、图片转为单通道

1、支持中文名称

cv2.imread替换为my_cv_imread

def my_cv_imread(filepath):
  #把图片数据导入到内存中,然后通过opencv从内存读入图片
  img = cv2.imdecode(np.fromfile(filepath, dtype=np.uint8), -1)
  return img

2、通道数转换

#通道数获取及转换
def cv_imread(file_path):
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
    if len(cv_img.shape)<3:
        temp = cv_img[:, :, np.newaxis]
        rslt = temp.repeat([3], axis=2)
        return rslt
    if cv_img.shape[2] == 4:
        rslt = np.asarray(Image.open(file_path).convert("RGB"))
        return rslt
    return cv_img

3、图片转为单通道

#图片转为单通道图,r g b设为某个像素值
def rgb2classImg2(input_path, save_path,classrgbDict):
    img_list = os.listdir(input_path)
    for image in img_list:
        img_path = os.path.join(input_path, image)
        save_path_img = os.path.join(save_path, image)
        img2 = Image.open(img_path)
        # img1 = Image.open(img_path)
        img2 = img2.convert('RGB')
        imgdata = img2.load()
        img3 = img2.convert('L')
        pixdata = img3.load()
      
        for y in range(img2.size[1]):
            for x in range(img2.size[0]):
                for item in classrgbDict:
                    if imgdata[x, y][0] == item["r"] and imgdata[x, y][1] == item["g"] and imgdata[x, y][2] ==item["b"]:
                        pixdata[x, y] = classrgbDict.index(item)
                    else:
                        pixdata[x, y] = len(classrgbDict)
        img3.save(save_path_img)


if __name__ == '__main__':
    input_path = r"D:\workSpace\pythonDataset\薯片\薯片1\out"
    save_path =  r"D:\workSpace\pythonDataset\薯片\薯片1\out2"
    classrgbDict = [{'label':'bg','r': 219.0, 'g': 121.0, 'b': 114.0,"a":0},{'label':'hair',"id":1,"r":255,"g":255,"b":0,"a":0}]
    rgb2classImg2(input_path, save_path,classrgbDict)

你可能感兴趣的:(python)