本文介绍: 【代码】Python OpenCV修改二值图像某特定颜色
#改变图片像素值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 ,0] != 0 or img[i ,j ,1] != 0 or img[i ,j ,2] != 0 ):
                img[i, j ,0] = 255
                img[i ,j ,1] = 255
                img[i ,j ,2] = 255


    return img
if __name__ =="__main__":
    filePath = 'D:weldlinecodedatasetVOCdevkit_v3_61VOC2012SegmentationClass/'
    savePath = 'D:weldlinecodedatasetVOCdevkit_v3_61VOC2012\new/'
    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)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(image_save_Path, img)

·上面那段代码有的图像会报错,下面这个代码也可以实现,记录一下。

import cv2
import cv2 as cv

#准备好需要替换颜色的图片yinzhang.jpg
img_rgb = cv2.imread('pictures/old/FeatureLocation5003.png')

Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

res, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)

#255为需要保留的颜色(即不被替换的颜色),利用掩膜思想覆盖黑色部分
img_rgb[mask == 0] = [255, 255, 255]

#cv2.imshow("imgOriginal", img_rgb) # show windows
cv2.imwrite('pictures/new/FeatureLocation5003.png', img_rgb, [int(cv2.IMWRITE_JPEG_QUALITY), 70])

##cv2.imshow("mask", mask) # show windows

#cv2.waitKey(0)

原文地址:https://blog.csdn.net/qq_40821469/article/details/135490463

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_53962.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注