def grab_cut(self, raw_image): number_of_interation = 5 channel_mask = np.zeros((raw_image.shape[0], raw_image.shape[1]), np.uint8) region_of_interest = (50, 50, 450, 290) background_model = np.zeros((1, 65), np.float64) foreground_model = np.zeros((1, 65), np.float64) mode_of_operation = cv2.GC_INIT_WITH_RECT cv2.grabCut(raw_image, channel_mask, region_of_interest, background_model, foreground_model, number_of_interation, mode_of_operation) normalization_mask = np.where( (channel_mask == 2) | (channel_mask == 0), 0, 1).astype('uint8') removed_background_image = raw_image * (normalization_mask[:, :, np.newaxis]) return removed_background_image
def redraw_grab_cut(self, gc_img): bgdmodel = np.zeros((1, 65), np.float64) fgdmodel = np.zeros((1, 65), np.float64) self.mask, _, __ = cv2.grabCut(gc_img, self.mask, self.rect, bgdmodel, fgdmodel, 5, cv2.GC_INIT_WITH_MASK) gp_plot = np.where((self.mask == 0) | (self.mask == 2), 0, 255).astype(np.uint8) self.score = dice_coef(self.label, gp_plot / 255) print(f'[DSC]: score f {self.score}') cv2.imshow('grab-cut', gp_plot)
def cut_background(img_src): """ @return x, y, w, h """ img = img_src.copy() h, w = img.shape[:2] # 背景填充 进行泛洪填充 mask = np.zeros((h + 2, w + 2), np.uint8) #掩码长和宽都比输入图像多两个像素点,满水填充不会超出掩码的非零边缘 cv2.floodFill(img, mask, (5, 5), (255, 255, 255), (3, 3, 3), (5, 5, 5), 8) # 去噪 img = cv2.fastNlMeansDenoisingColored(img, None, 20, 20, 7, 21) # 背景识别 mask = np.zeros((img.shape[:2]), np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) rect = (5, 5, w - 5, h - 5) # 多次计算,保证计算准确度 cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 1, cv2.GC_INIT_WITH_RECT) #关于where函数第一个参数是条件,满足条件的话赋值为0,否则是1。如果只有第一个参数的话返回满足条件元素的坐标。 mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') # 绘制轮廓 draw_img = img * mask2[:, :, np.newaxis] # 前景图使用白色填充,方便识别 draw_img[np.where((draw_img > [0, 0, 0]).all(axis=2))] = [255, 255, 255] # h, w = draw_img.shape[:2] draw_img = cv2.cvtColor(draw_img, cv2.COLOR_BGR2GRAY) #得到灰度图 _, binary = cv2.threshold(draw_img, 200, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if len(contours) < 1: return img else: max_countor = sorted(contours, key=cv2.contourArea, reverse=True)[0] return cv2.boundingRect(max_countor)
def cut_license(afterimg, rect): ''' 图像分割函数 ''' # 转换为宽度和高度 rect[2] = rect[2] - rect[0] rect[3] = rect[3] - rect[1] rect_copy = tuple(rect.copy()) rect = [0, 0, 0, 0] # 创建掩膜 mask = np.zeros(afterimg.shape[:2], np.uint8) # 创建背景模型 大小只能为13*5,行数只能为1,单通道浮点型 bgdModel = np.zeros((1, 65), np.float64) # 创建前景模型 fgdModel = np.zeros((1, 65), np.float64) # 分割图像 cv2.grabCut(afterimg, mask, rect_copy, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') img_show = afterimg * mask2[:, :, np.newaxis] return img_show
def grab_cut(): img = cv2.imread('3.jpg') mask = np.zeros(img.shape[:2], np.uint8) bgModel = np.zeros((1, 65), np.float64) fgModel = np.zeros((1, 65), np.float64) rect = (420, 1, 676, 881) cv2.grabCut(img, mask, rect, bgModel, fgModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') img = img * mask2[:, :, np.newaxis] plt.subplot(121) plt.title('Grabcut') plt.xticks([]), plt.yticks([]) plt.imshow(img) plt.subplot(122) plt.imshow(cv2.cvtColor(cv2.imread('3.jpg'), cv2.COLOR_BGR2RGB)) plt.title('Original') plt.xticks([]), plt.yticks([]) plt.show()
from cv2 import cv2 as cv import numpy as np from matplotlib import pyplot as plt img = cv.imread('image/front.jpg') ori = cv.cvtColor(img, cv.COLOR_BGR2RGB) x_, y_ = 99, 34 x__, y__ = 405, 311 mask = np.zeros(img.shape[:2], np.uint8) # 前后景模型 bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) rect = (x_, y_, x__, y__) # 获取第一个mask mask, bgdModel, fgdModel = cv.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv.GC_INIT_WITH_RECT) plt.subplot(141), plt.imshow(mask), plt.xticks([]), plt.yticks([]) # 一开始以为交互程序是要自己画矩形 # drawing = False # cv.namedWindow('win') # def draw(event, x, y, flags, param): # global x_, y_, drawing, rect, x__, y__ # if event == cv.EVENT_LBUTTONDOWN and drawing == False: # cv.circle(img, (x, y), 3, (0, 0, 255), 4) # x_, y_ = x, y # drawing = True # elif event == cv.EVENT_LBUTTONDOWN and drawing == True: # cv.rectangle(img, (x_, y_), (x, y), (0, 0, 255), 4)
cv2.imshow('Result', result) cv2.imshow('Foreground', fgMask) #get position of trackbar each time its moved kernel_val = cv2.getTrackbarPos('Blur', 'Masking') if kernel_val == 0: kernel_val = 1 if img1.drawingLineDone == True or img1.drawingRectDone == True or img1.blurSet == True: #perform grabcut to get mask depending on rect or line mask if img1.drawingRectDone == True: rect = [img1.x1, img1.y1, img1.x2, img1.y2] img1.mask, _, _ = cv2.grabCut(img1.main, img1.mask, rect, bgdModel, fgdModel, 5, mode=cv2.GC_INIT_WITH_RECT) elif img1.drawingLineDone == True: #create a mask with drawn outline and merge with rectangular mask img1.mask, _, _ = cv2.grabCut(img1.main, img1.mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK) #extract fg and bg from mask fgMask = np.where( (img1.mask == cv2.GC_BGD) | (img1.mask == cv2.GC_PR_BGD), 0, 1).astype('uint8') bgMask = np.where( (img1.mask == cv2.GC_FGD) | (img1.mask == cv2.GC_PR_FGD), 0, 1).astype('uint8')
# 검은색 영역은 배경이라고 확실하게 가정한 사각형의 바깥쪽 영역이며, 회색 영역은 그랩컷이 배경이라고 생각하는 영역, 흰색 영역은 전경 image_bgr = cv2.imread('../img/black.jpg') image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) # RGB로 변환 rectangle = (0, 56, 256, 150) # 사각형 좌표: 시작점의 x, 시작점의 y, 너비, 높이 mask = np.zeros(image_rgb.shape[:2], np.uint8) # 초기 마스크를 만듭니다. bgdModel = np.zeros((1, 65), np.float64) # grabCut에 사용할 임시 배열을 만듭니다. fgdModel = np.zeros((1, 65), np.float64) # 그랩컷(grabCut) 실행 cv2.grabCut( image_rgb, # 원본 이미지 mask, # 마스크 rectangle, # 사각형 bgdModel, # 배경을 위한 임시 배열 fgdModel, # 전경을 위한 임시 배열 5, # 반복 횟수 cv2.GC_INIT_WITH_RECT) # 사각형을 사용한 초기화 # 배경인 곳은 0, 그외에는 1로 설정한 마스크를 만듭니다. mask_2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') # 이미지에 새로운 마스크를 곱해 배경을 제외합니다. image_rgb_nobg = image_rgb * mask_2[:, :, np.newaxis] plt.imshow(image_rgb_nobg), plt.axis("off") # 이미지 출력 plt.show() plt.imshow(mask, cmap='gray'), plt.axis("off") # 마스크 출력 plt.show()
from cv2 import cv2 import numpy as np from PIL import Image in_path = r'D:\pythonVscode\people.jpg' out_path = r'D:\pythonVscode\photo_new.jpg' img = cv2.imread(in_path) rect = (0, 0, img.shape[0], img.shape[1]) mask = np.zeros(img.shape[:2], np.uint8) bgModel = np.zeros((1,65), np.float64) fgModel = np.zeros((1,65), np.float64) cv2.grabCut(img, mask, rect, bgModel, fgModel, 5, cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype(np.uint8) out = img * mask2[:, :, np.newaxis] #out += 255 * (1 - cv2.cvtColor(mask2, cv2.COLOR_GRAY2BGR)) cv2.imshow('output', out) cv2.waitKey() cv2.imwrite(out_path, out)
cv_img = [] for img in glob.glob( "/home/juan-rios/Documentos/python/trackMove/transparente/*.png"): n = cv2.imread(img) cv_img.append(n) #images = [cv2.imread(file) for file in glob.glob('/Users/jior/Desktop/iglue/trasparente/*.png')] background = Image.open( "/home/juan-rios/Documentos/python/trackMove/original/background.png") foreground = Image.open(img) size = 128, 128 background.paste(foreground, (0, 0)) background.show() final() '''img = cv2.imread('C:\\Users\\USUARIO\\Desktop\\iglue\\foto.png') mask = np.zeros(img.shape[:2],np.uint8) bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) rect = (50,50,450,290) cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT) mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') img = img*mask2[:,:,np.newaxis] plt.imshow(img),plt.colorbar(),plt.show() # newmask es la máscara etiquetada manualmente newmask = cv2.imread('C:\\Users\\USUARIO\\Desktop\\iglue\\foto.png',0) # donde sea que esté marcado en blanco (primer plano seguro), cambiar mask=1 # donde sea que esté marcado en negro (fondo seguro), cambiar mask=0 mask[newmask == 0] = 0 mask[newmask == 255] = 1
from cv2 import cv2 as cv from matplotlib import pyplot as plt import numpy as np img = cv.imread('image/front.jpg') mask = np.zeros(img.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) rect = (50, 50, 450, 290) # 函数的返回值是更新的 mask, bgdModel, fgdModel cv.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv.GC_INIT_WITH_RECT) mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8') img = img * mask2[:, :, np.newaxis] plt.imshow(img), plt.colorbar(), plt.show()
continue orig = image.copy() bods = entry.bodies # only working now for single rectangle if len(bods) == 1: bd = bods[0] # do first iterations of grabcut bgdmodel = numpy.zeros((1, 65), numpy.float64) fgdmodel = numpy.zeros((1, 65), numpy.float64) rect = get_rect(bd) mask = numpy.zeros(image.shape[:2], dtype=numpy.uint8) # mask initialized to BG cv2.grabCut(image, mask, rect, bgdmodel, fgdmodel, 5, cv2.GC_INIT_WITH_RECT) # second iterations of grabcut - sometimes it doesn't work try: cv2.grabCut(orig, mask, rect, bgdmodel, fgdmodel, 5, cv2.GC_INIT_WITH_MASK) except cv2.error as err: print(err) # make images with alpha channel b_channel, g_channel, r_channel = cv2.split(orig) # if probably background (2) or background (0), set to trasparent (0) # otherwise make opaque (255) a_channel = numpy.where((mask == 2) | (mask == 0), 0, 255).astype('uint8') foreground = cv2.merge((b_channel, g_channel, r_channel, a_channel))
import numpy as np from cv2 import cv2 from matplotlib import pyplot as plt img = cv2.imread('../image/FrontGround.jpg') img = cv2.resize(img, (800, 800)) orgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mask = np.zeros(img.shape[:2], np.uint8) # 制作黑色遮罩 bgd = np.zeros((1, 65), np.float64) fgd = np.zeros((1, 65), np.float64) rect = (70, 94, 631, 660) mask3 = cv2.grabCut(img, mask, rect, bgd, fgd, 5, cv2.GC_INIT_WITH_RECT)[0] # 缺少会导致边缘有缺损,矩阵模式 # mask6 = np.where((mask==2)|(mask==0),0,1).astype('uint8') # 如果图像中像素为2或0,则将其改0,否则改为1, # img = img*mask6[:,:,np.newaxis] # cv2.imwrite('../image/newmask.jpg',img) plt.subplot(221) plt.imshow(mask3) plt.axis('off') mask2 = cv2.imread('../image/newmask.jpg', 0) mask2 = cv2.resize(mask2, (800, 800)) # mask2Show = cv2.imread('../image/newmask.jpg',-1) # mask2Show = cv2.resize(mask2Show,(800,800)) # m2rgb=cv2.cvtColor(mask2Show,cv2.COLOR_BGR2RGB) mask[mask2 == 0] = 0 # 颜色映射 ,人工遮罩后的图片中被遮罩的部分 映射到 原图上,对原图进行遮罩 mask[mask2 == 255] = 1 # 这里使用自定义模板 plt.subplot(222) plt.imshow(mask3)
cv2.setMouseCallback('image', mouse_Callback) while True: cv2.imshow('image', show_img) k = cv2.waitKey(1) if k == ord('a') and not mouse_pressed: if w * h > 0: break cv2.destroyAllWindows() labels = np.full(img.shape[:2], cv2.GC_INIT_WITH_MASK, np.uint8) bgdModel = np.full(img.shape[:2], cv2.GC_PR_BGD, np.float64) fgdModel = np.full(img.shape[:2], cv2.GC_PR_FGD, np.float64) labels, bgdModel, fgdModel = cv2.grabCut(img, labels, (x, y, w, h), None, None, 1, cv2.GC_INIT_WITH_RECT) show_img = np.copy(img) show_img[(labels == cv2.GC_PR_BGD) | (labels == cv2.GC_BGD)] //= 3 cv2.imshow('image', show_img) cv2.waitKey() cv2.destroyAllWindows() label = cv2.GC_BGD lbl_clrs = {cv2.GC_BGD: (0, 0, 0), cv2.GC_FGD: (255, 255, 255)} def mouse_callback(event, x, y, flags, param): global mouse_pressed if event == cv2.EVENT_LBUTTONDOWN: