简体   繁体   English

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

[英]How to get rid of transparent background usign OpenCV 3 and Python 2.7?

I'm trying to remove the transparent background (the excess whitespace which is not visible here) from the last image. 我正在尝试从最后一张图片中删除透明背景(此处看不到多余的空白)。 It looks like this: 看起来像这样: 在此处输入图片说明

The code which I'm using is as follows: 我正在使用的代码如下:

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)

My question is, how do I remove the transparent background and just keep the phone's image? 我的问题是,如何删除透明背景并仅保留手机的图像?

I tried your code and it seems to do nothing. 我尝试了您的代码,但似乎无能为力。 Assuming that you want to crop out all the outer color pixels, here's my solution 假设您要裁剪所有外部彩色像素,这是我的解决方案

Get all point of interest: 获取所有兴趣点:

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))

Get the minimal rectangle: 获取最小矩形:

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

Use warpAffine to crop out the region of interest: 使用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)

And here's what we get 这就是我们得到的

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM