最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python+OpenCV實現(xiàn)圖像識別替換功能詳解

 更新時間:2022年07月14日 16:11:47   作者:阿濤的一天  
OpenCV-Python是一個Python庫,旨在解決計算機視覺問題。本文將利用Python+OpenCV實現(xiàn)圖像識別替換功能,感興趣的小伙伴可以動手嘗試一下

OpenCV-Python是一個Python庫,旨在解決計算機視覺問題。

OpenCV是一個開源的計算機視覺庫,1999年由英特爾的Gary Bradski啟動。Bradski在訪學過程中注意到,在很多優(yōu)秀大學的實驗室中,都有非常完備的內(nèi)部公開的計算機視覺接口。這些接口從一屆學生傳到另一屆學生,對于剛?cè)腴T的新人來說,使用這些接口比重復造輪子方便多了。這些接口可以讓他們在之前的基礎(chǔ)上更有效地開展工作。OpenCV正是基于為計算機視覺提供通用接口這一目標而被策劃的。

安裝opencv

pip3 install -i https://pypi.doubanio.com/simple/ opencv-python

思路:

1、首先區(qū)分三張圖片:

base圖片代表初始化圖片;

template圖片代表需要在大圖中匹配的圖片;

white圖片為需要替換的圖片。

2、然后template圖片逐像素縮小匹配,設(shè)定閾值,匹配度到達閾值的圖片,判定為在初始圖片中;否則忽略掉。

3、匹配到最大閾值的地方,返回該區(qū)域的位置(x,y)

4、然后用white圖片resize到相應的大小,填補到目標區(qū)域。

match函數(shù):

"""檢查模板圖片中是否包含目標圖片"""
def make_cv2(photo1, photo2):
    global x, y, w, h, num_1,flag
    starttime = datetime.datetime.now()
    #讀取base圖片
    img_rgb = cv2.imread(f'{photo1}')
    #讀取template圖片
    template = cv2.imread(f'{photo2}')
    h, w = template.shape[:-1]
    print('初始寬高', h, w)
    res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
    print('初始最大相似度', res.max())
    threshold = res.max()
    """,相似度小于0.2的,不予考慮;相似度在[0.2-0.75]之間的,逐漸縮小圖片"""
    print(threshold)
    while threshold >= 0.1 and threshold <= 0.83:
        if w >= 20 and h >= 20:
            w = w - 1
            h = h - 1
            template = cv2.resize(
                template, (w, h), interpolation=cv2.INTER_CUBIC)
            res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
            threshold = res.max()
            print('寬度:', w, '高度:', h, '相似度:', threshold)
        else:
            break
    """達到0.75覆蓋之前的圖片"""
    if threshold > 0.8:
        loc = np.where(res >= threshold)
        x = int(loc[1])
        y = int(loc[0])
        print('覆蓋圖片左上角坐標:', x, y)
        for pt in zip(*loc[::-1]):
            cv2.rectangle(
                img_rgb, pt, (pt[0] + w, pt[1] + h), (255, 144, 51), 1)
        num_1 += 1
        endtime = datetime.datetime.now()
        print("耗時:", endtime - starttime)
        overlay_transparent(x, y, photo1, photo3)
    else:
        flag = False

replace函數(shù):

"""將目標圖片鑲嵌到指定坐標位置"""
def overlay_transparent(x, y, photo1, photo3):
    #覆蓋圖片的時候上下移動的像素空間
    y += 4
    global w, h, num_2
    background = cv2.imread(f'{photo1}')
    overlay = cv2.imread(f'{photo3}')
    """縮放圖片大小"""
    overlay = cv2.resize(overlay, (w, h), interpolation=cv2.INTER_CUBIC)
    background_width = background.shape[1]
    background_height = background.shape[0]
    if x >= background_width or y >= background_height:
        return background
    h, w = overlay.shape[0], overlay.shape[1]
    if x + w > background_width:
        w = background_width - x
        overlay = overlay[:, :w]
    if y + h > background_height:
        h = background_height - y
        overlay = overlay[:h]
    if overlay.shape[2] < 4:
        overlay = np.concatenate([overlay, np.ones((overlay.shape[0], overlay.shape[1], 1), dtype=overlay.dtype) * 255],axis=2,)
    overlay_image = overlay[..., :3]
    mask = overlay[..., 3:] / 255.0
    background[y:y + h,x:x + w] = (1.0 - mask) * background[y:y + h,x:x + w] + mask * overlay_image
    # path = 'result'
    path = ''
    cv2.imwrite(os.path.join(path, f'1.png'), background)
    num_2 += 1
    print('插入成功。')
    init()

每次執(zhí)行需要初始化x,y(圖片匹配初始位置參數(shù)),w,h(圖片縮放初始寬高)

x = 0
y = 0
w = 0
h = 0
flag = True
threshold = 0
template = ''
num_1 = 0
num_2 = 0
photo3 = ''
"""參數(shù)初始化"""
def init():
    global x, y, w, h, threshold, template,flag
    x = 0
    y = 0
    w = 0
    h = 0
    threshold = 0
    template = ''

完整代碼

import cv2
import datetime
import os
import numpy as np
x = 0
y = 0
w = 0
h = 0
flag = True
threshold = 0
template = ''
num_1 = 0
num_2 = 0
photo3 = ''
"""參數(shù)初始化"""
def init():
    global x, y, w, h, threshold, template,flag
    x = 0
    y = 0
    w = 0
    h = 0
    threshold = 0
    template = ''

"""檢查模板圖片中是否包含目標圖片"""
def make_cv2(photo1, photo2):
    global x, y, w, h, num_1,flag
    starttime = datetime.datetime.now()
    img_rgb = cv2.imread(f'{photo1}')
    template = cv2.imread(f'{photo2}')
    h, w = template.shape[:-1]
    print('初始寬高', h, w)
    res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
    print('初始最大相似度', res.max())
    threshold = res.max()
    """,相似度小于0.2的,不予考慮;相似度在[0.2-0.75]之間的,逐漸縮小圖片"""
    print(threshold)
    while threshold >= 0.1 and threshold <= 0.83:
        if w >= 20 and h >= 20:
            w = w - 1
            h = h - 1
            template = cv2.resize(
                template, (w, h), interpolation=cv2.INTER_CUBIC)
            res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
            threshold = res.max()
            print('寬度:', w, '高度:', h, '相似度:', threshold)
        else:
            break
    """達到0.75覆蓋之前的圖片"""
    if threshold > 0.8:
        loc = np.where(res >= threshold)
        x = int(loc[1])
        y = int(loc[0])
        print('覆蓋圖片左上角坐標:', x, y)
        for pt in zip(*loc[::-1]):
            cv2.rectangle(
                img_rgb, pt, (pt[0] + w, pt[1] + h), (255, 144, 51), 1)
        num_1 += 1
        endtime = datetime.datetime.now()
        print("耗時:", endtime - starttime)
        overlay_transparent(x, y, photo1, photo3)
    else:
        flag = False


"""將目標圖片鑲嵌到指定坐標位置"""
def overlay_transparent(x, y, photo1, photo3):
    y += 0
    global w, h, num_2
    background = cv2.imread(f'{photo1}')
    overlay = cv2.imread(f'{photo3}')
    """縮放圖片大小"""
    overlay = cv2.resize(overlay, (w, h), interpolation=cv2.INTER_CUBIC)
    background_width = background.shape[1]
    background_height = background.shape[0]
    if x >= background_width or y >= background_height:
        return background
    h, w = overlay.shape[0], overlay.shape[1]
    if x + w > background_width:
        w = background_width - x
        overlay = overlay[:, :w]
    if y + h > background_height:
        h = background_height - y
        overlay = overlay[:h]
    if overlay.shape[2] < 4:
        overlay = np.concatenate([overlay, np.ones((overlay.shape[0], overlay.shape[1], 1), dtype=overlay.dtype) * 255],axis=2,)
    overlay_image = overlay[..., :3]
    mask = overlay[..., 3:] / 255.0
    background[y:y + h,x:x + w] = (1.0 - mask) * background[y:y + h,x:x + w] + mask * overlay_image
    # path = 'result'
    path = ''
    cv2.imwrite(os.path.join(path, f'1.png'), background)
    num_2 += 1
    print('插入成功。')
    init()


if __name__ == "__main__":
    photo1 = "1.png"
    photo2 = "3.png"
    photo3 = "white.png"

    while flag == True:
        make_cv2(photo1, photo2)
        overlay_transparent(x, y, photo1, photo3)

執(zhí)行結(jié)果:

到此這篇關(guān)于Python+OpenCV實現(xiàn)圖像識別替換功能詳解的文章就介紹到這了,更多相關(guān)Python OpenCV圖像識別替換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python?中的異步?for?循環(huán)示例詳解

    Python?中的異步?for?循環(huán)示例詳解

    這篇文章主要介紹了Python中的異步for循環(huán),我們將討論 Python 庫 asyncio 和運行異步代碼所需的函數(shù),需要的朋友可以參考下
    2023-05-05
  • python基礎(chǔ)之文件操作和異常處理

    python基礎(chǔ)之文件操作和異常處理

    這篇文章主要介紹了python基礎(chǔ)之文件操作和異常處理,文中有非常詳細的代碼示例,對正在學習python基礎(chǔ)的小伙伴們有一定的幫助,需要的朋友可以參考下
    2021-04-04
  • Python模塊Typing.overload的使用場景分析

    Python模塊Typing.overload的使用場景分析

    在 Python 中,typing.overload 是一個用于定義函數(shù)重載的裝飾器,函數(shù)重載是指在一個類中可以定義多個相同名字但參數(shù)不同的函數(shù),使得在調(diào)用函數(shù)時可以根據(jù)參數(shù)的不同選擇不同的函數(shù)執(zhí)行,這篇文章主要介紹了Python模塊Typing.overload的使用,需要的朋友可以參考下
    2024-02-02
  • Python實現(xiàn)的字典值比較功能示例

    Python實現(xiàn)的字典值比較功能示例

    這篇文章主要介紹了Python實現(xiàn)的字典值比較功能,可實現(xiàn)針對字典格式數(shù)據(jù)的判斷、比較功能,涉及Python字典格式數(shù)據(jù)的遍歷、判斷等相關(guān)操作技巧,需要的朋友可以參考下
    2018-01-01
  • Python之Django自動實現(xiàn)html代碼(下拉框,數(shù)據(jù)選擇)

    Python之Django自動實現(xiàn)html代碼(下拉框,數(shù)據(jù)選擇)

    這篇文章主要介紹了Python之Django自動實現(xiàn)html代碼(下拉框,數(shù)據(jù)選擇),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • python重要函數(shù)eval多種用法解析

    python重要函數(shù)eval多種用法解析

    這篇文章主要介紹了python重要函數(shù)eval多種用法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • Python 使用 docopt 解析json參數(shù)文件過程講解

    Python 使用 docopt 解析json參數(shù)文件過程講解

    這篇文章主要介紹了Python 使用 docopt 解析json參數(shù)文件過程講解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08
  • 詳解pyqt5 動畫在QThread線程中無法運行問題

    詳解pyqt5 動畫在QThread線程中無法運行問題

    這篇文章主要介紹了詳解pyqt5 動畫在QThread線程中無法運行問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • Python讀取和存儲yaml文件的方法

    Python讀取和存儲yaml文件的方法

    本文主要介紹了Python讀取和存儲yaml文件的方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Python繪制七彩花朵(用Turtle)

    Python繪制七彩花朵(用Turtle)

    這篇文章主要給大家介紹了關(guān)于Python使用Turtle繪制七彩花朵的相關(guān)資料,通過本文介紹的方法就算剛?cè)腴T的朋友也可以很快的入手繪制出漂亮的七彩花朵,需要的朋友可以參考下
    2023-07-07

最新評論

赤峰市| 锦屏县| 诏安县| 大连市| 栾城县| 营山县| 阳原县| 嘉义市| 闽侯县| 西城区| 孝昌县| 溆浦县| 长宁县| 琼中| 福鼎市| 德令哈市| 吉首市| 黔西| 沭阳县| 栖霞市| 拉萨市| 育儿| 托克逊县| 无棣县| 清苑县| 庄河市| 浑源县| 甘德县| 嘉祥县| 鹰潭市| 萝北县| 常州市| 曲麻莱县| 营山县| 来安县| 象山县| 麻栗坡县| 东方市| 两当县| 松溪县| 蕉岭县|