实例分割中物品遮挡数据增强实现

import os
import cv2
import numpy as np


def proces(img,mask):
    maskcopy = mask.copy()
    indexs = np.array(np.where(mask > 0)[:-1])
    x1 = np.min(indexs[1])
    y1 = np.min(indexs[0])
    x2 = np.max(indexs[1])
    y2 = np.max(indexs[0])
    w = x2 - x1
    h = y2 - y1
    if w > h:
        randw = np.random.randint(w // 15,w//3)
        startx = np.random.randint(x1 + w // 15,x2-w // 15-randw)
        mask[y1:y2,startx:startx + randw] = 0
    else:
        randh = np.random.randint(h // 15,h // 3)
        starth = np.random.randint(y1 + h // 15,y2 - h // 15 - randh)
        mask[starth:starth + randh,x1:x2] = 0
    dif = maskcopy - mask
    index = np.where(dif > 0)
    img[index] = 128


for dir in os.listdir('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/masks'):
    img = cv2.imread('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/jpg/{}.jpg'.format(dir))
    if not os.path.exists('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newmasks/{}'.format(dir)):
        os.mkdir('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newmasks/{}'.format(dir))
    for file in os.listdir('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/masks/{}'.format(dir)):
        mask = cv2.imread('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/masks/{}/{}'.format(dir, file))
        if 'None' in file:
            proces(img,mask)
        mmask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
        ret, mmask = cv2.threshold(mmask, 127, 255, cv2.THRESH_BINARY)
        binary = np.zeros_like(mask)
        contours, hierarchy = cv2.findContours(mmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        contours = np.array(contours)
        if not os.path.exists('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newtxts/{}'.format(dir)):
            os.mkdir('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newtxts/{}'.format(dir))
        cv2.imwrite('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newmasks/{}/{}'.format(dir,file),mask)
        np.save('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newtxts/{}/{}.npy'.format(dir,file),contours)
    cv2.imwrite('/home/lixuan/workspace/dataset/icecreamtwo/labelme_train/news/newjpg/{}.jpg'.format(dir),img)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值