Home > Net >  How can I change background color to red of an image using Python
How can I change background color to red of an image using Python

Time:04-10

I have the following code that works great but it doesn't fill all background. I played with numbers but it either makes all image red or not changing the background.
How can I change the background color of the image?

Picture i want to change it's background]:
enter image description here

import cv2
import numpy as np
from google.colab import drive
drive.mount('/content/drive')
image=cv2.imread('/content/drive/MyDrive/tulips.jpg')
r = 720.0 / image.shape[1]
dim = (720, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
lower_white = np.array([80, 1, 1],np.uint8) #lower hsv value
upper_white = np.array([130, 255, 255],np.uint8) #upper hsv value
hsv_img = cv2.cvtColor(resized,cv2.COLOR_BGR2HSV)#rgb to hsv color space
#filter the background pixels 

frame_threshed = cv2.inRange(hsv_img, lower_white, upper_white) 

kernel = np.ones((5,5),np.uint8) 

dilation = cv2.dilate(frame_threshed,kernel,iterations = 2)
resized[dilation==255] = (0,0,255) #convert background color
cv2_imshow(resized)

after this code i get this image:
enter image description here

CodePudding user response:

I thought we can simply use enter image description here

thesh after morphological opening, and floodFill:
enter image description here

Output image:
enter image description here

  • Related