python
#改变图片像素值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:\weldline\code\dataset\VOCdevkit_v3_61\VOC2012\SegmentationClass/'
savePath = 'D:\weldline\code\dataset\VOCdevkit_v3_61\VOC2012\\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)
·上面那段代码有的图像会报错,下面这个代码也可以实现,记录一下。
python
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)