计算机系统应用教程网站

网站首页 > 技术文章 正文

14.OpenCV-图像背景更换

btikc 2024-12-09 10:55:56 技术文章 18 ℃ 0 评论

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

import cv2
imgfile="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: 阈值,是一个值,通常为127
  • maxval: 当图像超过了阈值或低于阈值(由type决定),所赋予的值
  • cv2.THRESH_BINARY 二值法,超过阈值thresh部分取maxval(设定的最大值),否则取0

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表