【发布时间】: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