龙空技术网

14.OpenCV-图像背景更换

UNET 105

前言:

此时看官们对“opencv去除图像背景”都比较着重,各位老铁们都想要知道一些“opencv去除图像背景”的相关知识。那么小编同时在网上搜集了一些关于“opencv去除图像背景””的相关文章,希望看官们能喜欢,朋友们快快来学习一下吧!

视频:14.1 OpenCV-图像背景更换

原图

import cv2imgfile="img/andy1.jpg"#读取图像数据BGR模式img=cv2.imread(imgfile)# BGR模式转灰度gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#做二值化处理ret,thresh=cv2.threshold(gray,180,255,cv2.THRESH_BINARY) #二值化#mask=cv2.erode(thresh,None,iterations=5)#遍历thresh白色区域部分for i in range(thresh.shape[0]):    for j in range(thresh.shape[1]):        if thresh[i,j]==255:            img[i,j]=[255,0,0]#替换成想要的背景颜色cv2.imshow("img",img)cv2.imshow("thresh",thresh)#cv2.imshow("mask",mask)cv2.waitKey(0)cv2.destroyAllWindows()

运行结果

#图像二值化    def imgthreshold():    img=cv2.imread("img/s4.jpg")    img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)        ret,thresh1=cv2.threshold(img,127,255,cv2.THRESH_BINARY)    ret,thresh2=cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)    ret,thresh3=cv2.threshold(img,127,255,cv2.THRESH_TRUNC)    ret,thresh4=cv2.threshold(img,127,255,cv2.THRESH_TOZERO)    ret,thresh5=cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)       title=[0,1,2,3,4,5]    imgcv=[img,thresh1,thresh2,thresh3,thresh4,thresh5]    images=list(map(lambda x:Image.fromarray(cv2.cvtColor(x,cv2.COLOR_BGR2RGB)),imgcv))    for i in range(6):        plt.subplot(2,3,i+1)                plt.imshow(images[i])        plt.title(title[i])        plt.xticks([])        plt.yticks([])    plt.show()

图像阈值处理函数:

ret, dst = cv2.threshold(src, thresh, maxval, type)

src: 输入图,只能输入单通道图像,通常是灰度图dst: 输出图thresh: 阈值,是一个值,通常为127maxval: 当图像超过了阈值或低于阈值(由type决定),所赋予的值cv2.THRESH_BINARY 二值法,超过阈值thresh部分取maxval(设定的最大值),否则取0

标签: #opencv去除图像背景