如何使用 Python 将图像的背景颜色更改为红色

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

我有以下代码,效果很好,但它没有填满所有背景。我玩过数字,但它要么使所有图像变红,要么不改变背景。
如何更改图片的背景颜色?

图片我想改变它的背景]:

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)

在这段代码之后我得到了这张图片:

我想我们可以简单地使用 cv2.floodFill,然后用红色填充白色背景。
问题是图像不够干净 - 存在 JPEG 瑕疵和粗糙的边缘。

使用cv2.inRange可能会让我们更接近,但假设有一些白色郁金香(我们不想变成红色),我们可能不得不使用floodFill来填充背景。

我想出了以下阶段:

  • 从 RGB 转换为 HSV 颜色 space。
  • 在饱和度通道上应用阈值 - 白色背景在 HSV 颜色中几乎为零 space。
  • 应用开放形态学操作去除伪像。
  • 在阈值图像上应用 floodFill - 用值 128 填充背景。
    背景要128.
    郁金香区域内的黑色像素将为 0。
    大部分郁金香区域保持白色。
  • 将阈值等于 128 的所有像素设置为红色。

代码示例:

import cv2
import numpy as np
image = cv2.imread('tulips.jpg')

# Fill the black background with white color
#cv2.floodFill(image, None, seedPoint=(0, 0), newVal=(0, 0, 255), loDiff=(2, 2, 2), upDiff=(2, 2, 2))  # Not working!

hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)  # rgb to hsv color space

s_ch = hsv_img[:, :, 1]  # Get the saturation channel

thesh = cv2.threshold(s_ch, 5, 255, cv2.THRESH_BINARY)[1]  # Apply threshold - pixels above 5 are going to be 255, other are zeros.
thesh = cv2.morphologyEx(thesh, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)))  # Apply opening morphological operation for removing artifacts.

cv2.floodFill(thesh, None, seedPoint=(0, 0), newVal=128, loDiff=1, upDiff=1)  # Fill the background in thesh with the value 128 (pixel in the foreground stays 0.

image[thesh == 128] = (0, 0, 255)  # Set all the pixels where thesh=128 to red.

cv2.imwrite('tulips_red_bg.jpg', image)  # Save the output image.

s_ch(饱和色通道):

thesh 形态开后,floodFill:

输出图像: