I want a python script to change the background to black of a image of onion, how can it be done?

97 Views Asked by At

I am trying to change the background colour of a onion image to black

I tried to write the code in python using opencv and pixellib but it won’t work and I am expecting some help to change this

1

There are 1 best solutions below

0
Miladfa7 On

To change the background color of an onion image to black using openCV and pixellib:

import cv2

img = cv2.imread('onion.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=3)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel, iterations=2)

result = cv2.bitwise_not(opening)

cv2.imwrite('onion_black.jpg', result)