import cv2
import numpy as np
import os
import os.path as osp
import random
from random import choice
#复制原图!!!切割部分同时覆盖背景原图和分割图
img_dirs = "/切割原图文件夹/data/select_segcolors/none"
backimg_dirs = "/背景图文件夹/data/1/images_copy"
gtsem_dirs = "/分割图文件夹/data/gt_semantic_copy"
#saveDirs = img_dirs.replace("limit_lever", "generator_img/1")
#os.makedirs(saveDirs, exist_ok=True)
#savegtsem_Dirs = "/data/gtsem_test"
#os.makedirs(savegtsem_Dirs, exist_ok=True)
###随机选择3张背景原图粘贴想要的切割原图
pathDir = os.listdir("/背景图文件夹/data/1/selectimg")
sample = random.sample(pathDir, 3)
index = 0
for backImg in sample:
for name in os.listdir(img_dirs):
backImg_path = osp.join(backimg_dirs, backImg)
#print("backImg_path:", backImg_path)
img_back = cv2.imread(backImg_path)
img_back = cv2.cvtColor(img_back, cv2.COLOR_BGR2RGB)
#rows, cols, channels = img_back.shape
#print("backImg height:", rows, "weight:", cols)
(path, filename) = os.path.split(backImg_path)
file_name, extension = os.path.splitext(filename)
#print(filename)
gtsem = (file_name + ".png")
gtsem_path = osp.join(gtsem_dirs, gtsem)
print("gtsem_path:", gtsem_path)
gtsem_img = cv2.imread(gtsem_path)
gtsem_img = cv2.cvtColor(gtsem_img, cv2.COLOR_BGR2RGB)
#rows, cols, channels = gtsem_img.shape
#print("gtsem_img height:", rows, "weight:", cols)
img_path = osp.join(img_dirs, name)
#print("img_path:", img_path)
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
w, h = img.shape[0:2]
# os.path.split()返回文件的路径和文件名
(filepath, tempfilename) = os.path.split(img_path)
#print(tempfilename)
# os.path.splitext()将文件名和扩展名分开
fname, fename = os.path.splitext(tempfilename)
#print(fname)
#print("img height:", w, "weight:", h)
# img=cv2.erode(img,None,iterations=1)
# img=cv2.dilate(img,None,iterations=1)
center=[0,0]#在新背景图片中的位置
###在切割原图中遍历像素值从而覆盖背景原图与分割图
for i in range(w):
for j in range(h):
if img[i][j][0] < 10 and img[i][j][1] < 10 and img[i][j][2] < 10:#0代表黑色的点
continue
else:
#对于背景原图此处替换切割原图颜色
img_back[center[0]+i, center[1]+j] = img[i, j]
#对于分割图此处替换切割图处分割像素值
gtsem_img[i][j][0] = 255
gtsem_img[i][j][1] = 255
gtsem_img[i][j][2] = 0
savepath = osp.join(backimg_dirs, fname + backImg)
cv2.imwrite(savepath, cv2.cvtColor(img_back, cv2.COLOR_BGR2RGB))
savegtsem_path = osp.join(gtsem_dirs, fname + gtsem)
cv2.imwrite(savegtsem_path, cv2.cvtColor(gtsem_img, cv2.COLOR_BGR2RGB))
print("save ", fname + backImg, "to ", savepath)
print("save ", fname + gtsem, "to ", savegtsem_path)
# randomlist.remove(one)
print("congratulations--------*done*")
cutAndPastPicture 切割部分同时覆盖背景原图和分割图
最新推荐文章于 2026-01-07 13:36:22 发布
此篇博客介绍了一个使用Python的方法,通过随机选择背景图片并粘贴切割原图,同时更新背景和分割图的特定像素。作者展示了如何读取和操作图像文件,并利用OpenCV进行颜色替换和图像保存。
1万+

被折叠的 条评论
为什么被折叠?



