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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.