import os
import os.path as osp
from PIL import Image
import numpy as np
import cv2
import matplotlib
import matplotlib.image as img
dirs = "/分割图文件夹/data/gt_semantic1"
source = "/原图文件夹/data/1/images"
saveDirs = dirs.replace("gt_semantic1", "select_segcolors")
os.makedirs(saveDirs, exist_ok=True)
for name in os.listdir(dirs):
img_path = osp.join(dirs, name)
gt = Image.open(img_path)
img_array = np.array(gt)
w = gt.size[0]
h = gt.size[1]
###把想选择出的颜色处像素值置为1,其他处置为0
for i in range(0, h):
for j in range(0, w):
# if 0.95 <= img_array[i][j][0] / 170 <= 1.05 and 0.95 <= img_array[i][j][1] / 240 <= 1.05 and 0.95 <= img_array[i][j][2] / 209 <= 1.05:
# if img_array[i][j][0] / 250 == 1 and img_array[i][j][1] / 50 == 1 and img_array[i][j][2] / 183 == 1:
if img_array[i][j][0] == 255 and img_array[i][j][1] == 0 and img_array[i][j][2] == 0:
img_array[i][j][0] = 1
img_array[i][j][1] = 1
img_array[i][j][2] = 1
else:
img_array[i][j][0] = 0
img_array[i][j][1] = 0
img_array[i][j][2] = 0
###把修改后的分割图的img_array*原图的array,那么想选出的颜色1乘以原像素值还是原像素值,0乘以原像素值为0,可以留下原图中想要的物体
if np.all(img_array == 0):
continue
else:
# os.path.splitext()将文件名和扩展名分开
fname, fename = os.path.splitext(name)
fname = (fname + ".jpg")
sourceImg_path = osp.join(source, fname)
sourceImg = Image.open(sourceImg_path)
sourceImg_array = np.array(sourceImg)
segImg = cv2.multiply(img_array, sourceImg_array)
cv2.imwrite(osp.join(saveDirs, fname), cv2.cvtColor(segImg, cv2.COLOR_BGR2RGB))
print("%s save done"%(fname))
print("congratulations---done!")
通过分割图留下原图中物体
于 2022-05-13 14:55:12 首次发布
该博客介绍了通过Python进行图像处理的方法。首先,从指定文件夹加载分割图,然后读取原图。接着,遍历图像矩阵,将特定颜色(红色)的像素值置为1,其余置为0。之后,通过将修改后的分割图与原图按元素相乘,保留原图中红色区域。最后,将处理后的图像保存,并输出完成信息。
摘要由CSDN通过智能技术生成