通过分割图留下原图中物体

该博客介绍了通过Python进行图像处理的方法。首先,从指定文件夹加载分割图,然后读取原图。接着,遍历图像矩阵,将特定颜色(红色)的像素值置为1,其余置为0。之后,通过将修改后的分割图与原图按元素相乘,保留原图中红色区域。最后,将处理后的图像保存,并输出完成信息。
摘要由CSDN通过智能技术生成
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!")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值