简体   繁体   中英

Remove white background from image with opencv python

I have been trying to remove background from a logo and use it as a watermark on product images.I tried to remove background from logo with masking but it also removing black fonts from logo. i need help in removing background without changing the logo. images are attached below. output image is the image i get as output with this code. logo image: https://drive.google.com/file/d/1yMG6cDuPt8q3EqOJ4Amzp_czWq5hrGS5/view?usp=sharing product image: https://drive.google.com/file/d/13SmkTgBtWD3yIJq-qGI0aZJ-hjaLbyuB/view?usp=sharing output image: https://drive.google.com/file/d/1k-fQ9tPUEJKQXPdmdB2ajtliAAG4irNs/view?usp=sharing

this is my code

import cv2
import numpy as np
img = cv2.imread('images/1L2Z3A443AAMC.jpg')
logo = cv2.imread('water2.png')
logo = cv2.resize(logo,(int(img.shape[0]/1.2),int(img.shape[1]/2)))
logo_gray = cv2.cvtColor(logo,cv2.COLOR_BGR2GRAY)
ret,mask= cv2.threshold(logo_gray,245,255,cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
logo_final = cv2.bitwise_and(logo,logo, mask=mask_inv)


h_img,w_img,_ = img.shape
h_logo,w_logo,_ = logo.shape
center_y = int(h_img/2)
center_x = int(w_img/2)
top_y = center_y - (int(h_logo/2)) 
left_x = center_x - (int(w_logo/2)) 
bottom_y = top_y + h_logo
right_x = left_x + w_logo

roi = img[top_y:bottom_y,left_x:right_x]
result = cv2.addWeighted(roi,1,logo_final,1,0)
img[top_y:bottom_y,left_x:right_x] = result
cv2.imwrite('sample.jpg',img)

In order to remove the background from a logo. We need to used masking. A masking for the foreground and another masking for the background.

logo = cv2.imread("water2.png", -1)
logo_mask = logo[:,:,3]
logo_mask_inv = cv2.bitwise_not(logo_mask)
logo = logo[:,:,0:3]

logo_background = cv2.bitwise_and(roi, roi, mask=logo_mask_inv)
logo_foreground = cv2.bitwise_and(logo, logo, mask=logo_mask)
final_logo = cv2.add(logo_background, logo_foreground)

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.

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