日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python OpenCV 交互式前景提取 自动抠图

發布時間:2024/3/26 python 55 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python OpenCV 交互式前景提取 自动抠图 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這是需要摳圖的原圖像,文件名為 “messi5.jpg”

?使用矩形方式處理:

# -*- coding: utf-8 -*-import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('messi5.jpg') # 返回一個和圖片等尺寸、且全為0的矩陣 mask = np.zeros(img.shape[:2],np.uint8)# 返回1*65、且全為0的矩陣 # grabCut 算法用到,無需關心 bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64)# 前景在矩形框以內 rect = (64,67,467,355) # 函數的返回值是更新的 mask, bgdModel, fgdModel # https://blog.csdn.net/github_39611196/article/details/81143026 # mask 掩碼圖像,用于確定哪些可能是前景/背景 # rect 前景矩形,格式為 (x1,y1,x2,y2) # 5 算法迭代次數 # cv2.GC_INIT_WITH_?? 前景提取模式是矩形形式還是掩碼的形式 cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)# 根據是否條件滿足,返回元素為0/1的數組 mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') # np.newaxis 增加一個維度, # 將二維2*3的矩陣 [[0 0 0] [0 0 0]] 變成 # 三維2*3*1的矩陣 [ [ [0] [0] [0] ] [ [0] [0] [0] ] ] # print(mask2) # print('\nwaxis\n',mask2[:,:,np.newaxis].shape) # 數組相乘,得到每個元素的乘積 img = img*mask2[:,:,np.newaxis]plt.imshow(img),plt.colorbar(),plt.show()

使用矩形模式 圖像處理結果:

使用掩模方式處理:

打開網址 :https://www.tuyitu.com/photoshop/

將原圖像上傳,新建圖層,繪制前景-背景掩模圖像:

繪制方式為:一定是前景-白色;一定是背景-黑色;可能是背景-灰色(144色值)

保存掩模圖層,命名為 “newmask.png”?

?執行下列程序:

?

# -*- coding: utf-8 -*-import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('messi5.jpg') # 返回一個和圖片等尺寸、且全為0的矩陣 mask = np.zeros(img.shape[:2],np.uint8)# 返回1*65、且全為0的矩陣bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) rect = (64,67,467,355) # newmask is the mask image I manually labelled newmask = cv2.imread('newmask.png',0) # whereever it is marked white (sure foreground), change mask=1 # whereever it is marked black (sure background), change mask=0 # 黑色一定是背景 mask[newmask == 0] = 0 # 白色一定是前景 mask[newmask == 255] = 1 # 灰色可能是背景 mask[newmask == 145] = 2# 打印看看灰色色值 print(newmask[:,100])# 注意 newmask 一定是按要求的圖層保存,否則函數會錯誤 # 建議使用Photoshop或在線PS工具:https://www.tuyitu.com/photoshop/ # 函數的返回值是更新的 mask, bgdModel, fgdModel # mask 掩碼圖像,用于確定哪些可能是前景/背景 # None 前景矩形,未用到 # 5 算法迭代次數 # GC_INIT_WITH_MASK 掩碼的形式提取 mask, bgdModel, fgdModel = cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK) mask = np.where((mask==2)|(mask==0),0,1).astype('uint8') img = img*mask[:,:,np.newaxis] plt.imshow(img),plt.colorbar(),plt.show()

處理圖像結果:

直接使用掩模方式,只需在圖像中畫上幾筆,就可以將前景人物完美提取出來,可見 grabCut 函數非常強大。

參考資料:OpenCV官方教程中文版(For Python).pdf

?

?

?

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的Python OpenCV 交互式前景提取 自动抠图的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。