【问题标题】:How to get rid of transparent background usign OpenCV 3 and Python 2.7?如何使用 OpenCV 3 和 Python 2.7 去除透明背景?
【发布时间】:2017-03-31 09:43:51
【问题描述】:

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

我使用的代码如下:

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)

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

【问题讨论】:

  • 所以你想把图片裁剪成手机大小?
  • 是的,但我不想使用任何硬编码值。
  • 请阅读How to Ask。你没有提到你的解决方案有什么问题。您是否希望我们运行您的代码并测试它是否正常工作?为什么不告诉我们?

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


【解决方案1】:

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

获取所有兴趣点:

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)

这就是我们得到的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2013-02-24
    • 2021-03-29
    • 2010-10-15
    • 2020-01-13
    • 2021-11-03
    • 2021-11-07
    相关资源
    最近更新 更多