亲宝软件园·资讯

展开

opencv转换颜色空间更改图片背景

人气:0

思路:

1、将BGR转换为HSV颜色空间
2、设置掩模
3、位运算

这里以更改摩托罗拉logo背景为例,图片在必应图片搜索得知,具体代码如下:

import numpy as np
import cv2
from imageio import imread
import matplotlib.pyplot as plt

def show(img,winname = "img"):
 cv2.namedWindow(winname,cv2.WINDOW_GUI_NORMAL)
 cv2.imshow(winname,img)
 cv2.waitKey(0)
 cv2.destroyAllWindows()

imgpath = r'motorola.jpg'

img = imread(imgpath)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
if img.shape == 4:
 img = img[:,:,:3]

show(img)
print(img.shape)

bgd = np.ones(img.shape,dtype=np.uint8)
bgd[:,:,:] = 255 #转换为白色背景
show(bgd,"white")
# 转换颜色空间
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
# show(hsv)
# 绿色分量掩模,使用inRange函数
# lowergreen = np.array([35,43,46],dtype = np.uint8)
# uppergreen = np.array([77,255,255],dtype=np.uint8)
# maskgreen = cv2.inRange(hsv,lowergreen,uppergreen)
# show(maskgreen)

# 蓝色分量掩模,使用inRange函数
lowerblue = np.array([100,43,46],dtype = np.uint8)
upperblue = np.array([124,255,255],dtype=np.uint8)
maskblue = cv2.inRange(hsv, lowerblue, upperblue)
maskblue_inv = cv2.bitwise_not(maskblue)
show(maskblue,'maskblue')
show(maskblue_inv,'maskblue_inv')
# 腐蚀操作
kernel_erode = np.ones((3,3),dtype = np.uint8)
erode = cv2.erode(maskblue,kernel_erode)

# 膨胀操作
kernel_dilate = np.ones((5,5),np.uint8)
dilate = cv2.dilate(erode, kernel = kernel_dilate)

show(erode,'erode')

# 前景色只留下蓝色字体部分
fg = cv2.bitwise_and(img,img,mask = maskblue)
show(fg,'fg')
# 背景中除去蓝色字体部分
bg = cv2.bitwise_and(bgd,bgd,mask = maskblue_inv)
show(bg,'bg')
# 前景色和背景色相加
dst = cv2.add(bg,fg)
show(dst,'dst')
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论