如何摆脱透明背景使用OpenCV 3和Python 2.7?

时间:2017-03-31 09:43:51

标签: python python-2.7 opencv ubuntu image-processing

我正在尝试从最后一张图片中删除透明背景(此处不可见的多余空白)。它看起来像这样: enter image description here

我正在使用的代码如下:

import cv2
import numpy as np
import os
from matplotlib import pyplot as plt

##Change directory to desktop
os.chdir("/home/meh/Desktop/")


##Reading the image
img_gray_scale = cv2.imread('img2.jpg',0)
img_colored = cv2.imread('img2.jpg',1)


###CONTOURS FOR IMAGE SEGMENTAITON####
##Gray scale image must be used
ret, thresh =     cv2.threshold(img_gray_scale,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy =     cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)


####Extracting just the ROI
###First argument img is the source of image
###Second is the countours which should be passed as python list
###Third is index of contours (to draw all contours pass -1)
####remaining are color and thickness
mask2 = cv2.drawContours(thresh, contours, 0, (255,0,0), -1)

masked_data = cv2.bitwise_and(img_gray_scale,img_gray_scale, mask = mask2)

b,g,r = cv2.split(img_colored)
rgba = [b,g,r, thresh]
dst = cv2.merge(rgba,4)

cv2.imwrite('phone_original_without_background.png',dst)



dst = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
cv2.imwrite('phone_grayscale_without_background.png',dst)

我的问题是,如何删除透明背景并保留手机的图像?

1 个答案:

答案 0 :(得分:0)

我尝试了你的代码,似乎什么也没做。假设你要裁剪掉所有外部颜色像素,这就是我的解决方案

获取所有兴趣点:

height,width = img_gray_scale.shape

fg = []

for col in range(width):
    for row in range(height):
        if thresh[row][col] < 255:
            fg.append((col,row))

获取最小矩形:

rotatedRect = cv2.minAreaRect(np.array(fg))

使用warpAffine裁剪出感兴趣的区域:

def subimage2(image, rotatedRect):
    center, rotatedRect, angle = rotatedRect
    width,height = int(shape[0]),int(shape[1])

    # convert angle to radian and build affine transformation mat
    theta = angle * np.pi/180
    cosine,sine = np.cos(theta), np.sin(theta)
    mapping = np.array([[cosine, sine, -center[0]+width/2],
                        [-sine, cosine, -center[1]+height/2]])

    # write output
    return cv2.warpAffine(image,mapping,(width,height))

cropped = subimage2(dst,rotatedRect)

这就是我们得到的东西

enter image description here