OpenCV-Python是一個Python庫,旨在解決計算機視覺問題。那么,很多的小伙伴都有興趣了解一下吧,正好,小編給大家總結(jié)了關(guān)于這方面的一些代碼問題,本文將利用Python+OpenCV實現(xiàn)圖像識別替換功能,小伙伴們在讀完之后,可以自己動手實踐一下哦。
OpenCV-Python是一種Python庫,目的在于處理機器視覺難題。
OpenCV可以說是開源系統(tǒng)的機器視覺庫,1999年于intel的GaryBradski啟動。Bradski在訪學(xué)時候留意到,在大多數(shù)優(yōu)秀大學(xué)的實驗室中,都會有相當(dāng)完善的內(nèi)部公開的機器視覺接口。這類接口從一屆學(xué)生傳至另一屆學(xué)生,針對初入行的小白而言,利用這些接口比重復(fù)造輪子方便很多。這類接口能讓他們在之前的基礎(chǔ)上更有效地開展工作。OpenCV正是基于為機器視覺提供通用接口這一目標(biāo)而被策劃的。
安裝opencv
pip3 install -i https://pypi.doubanio.com/simple/ opencv-python
思路:
1、首先區(qū)分三張圖片:
base圖片代表初始化圖片;
template圖片代表需要在大圖中匹配的圖片;
white圖片為需要替換的圖片。
2、然后template圖片逐像素縮小匹配,設(shè)定閾值,匹配度到達(dá)閾值的圖片,判定為在初始圖片中;否則忽略掉。
3、匹配到最大閾值的地方,返回該區(qū)域的位置(x,y)
4、然后用white圖片resize到相應(yīng)的大小,填補到目標(biāo)區(qū)域。
match函數(shù):
"""檢查模板圖片中是否包含目標(biāo)圖片"""
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
"""達(dá)到0.75覆蓋之前的圖片"""
if threshold > 0.8:
loc = np.where(res >= threshold)
x = int(loc[1])
y = int(loc[0])
print('覆蓋圖片左上角坐標(biāo):', 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ù):
"""將目標(biāo)圖片鑲嵌到指定坐標(biāo)位置"""
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 = ''
"""檢查模板圖片中是否包含目標(biāo)圖片"""
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
"""達(dá)到0.75覆蓋之前的圖片"""
if threshold > 0.8:
loc = np.where(res >= threshold)
x = int(loc[1])
y = int(loc[0])
print('覆蓋圖片左上角坐標(biāo):', 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
"""將目標(biāo)圖片鑲嵌到指定坐標(biāo)位置"""
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ī)韼椭?/font>
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/127547.html
摘要:時間永遠(yuǎn)都過得那么快,一晃從年注冊,到現(xiàn)在已經(jīng)過去了年那些被我藏在收藏夾吃灰的文章,已經(jīng)太多了,是時候把他們整理一下了。那是因為收藏夾太亂,橡皮擦給設(shè)置私密了,不收拾不好看呀。 ...
摘要:美國開國領(lǐng)袖們?nèi)绻吹矫绹癖娭荒茉谙@锖痛ㄆ罩羞x擇,估計要集體氣活過來。本教程由發(fā)布在實驗樓,完整教程及在線練習(xí)地址川普撞臉希拉里基于的面部特征交換一教程介紹內(nèi)容簡介通過庫來實現(xiàn)人臉面部特征交換。 話說這次美國大選可謂賺足了眼球,在美國史上,恐怕沒有哪一年的總統(tǒng)大選會像今年一樣詭譎和熱鬧。 美國開國領(lǐng)袖們?nèi)绻吹矫绹癖娭荒茉谙@锖痛ㄆ罩羞x擇,估計要集體氣活過來。作為一個閑得蛋疼...
摘要:的文本檢測器是一種基于新穎架構(gòu)和訓(xùn)練模式的深度學(xué)習(xí)模型。深度學(xué)習(xí)文本檢測器圖文本檢測全卷積網(wǎng)絡(luò)的結(jié)構(gòu)等人的圖。隨著和的發(fā)布,我們現(xiàn)在可以使用一種名為的基于深度學(xué)習(xí)的文本檢測器,它基于等人的年論文一種高效精確的場景文本檢測器。 by Adrian Rosebrock on August 20, 2018 in Deep Learning, Optical Character Recogn...
摘要:了解華為海思的方案海思的前身是華為的半導(dǎo)體部門,主要產(chǎn)品線包括智能手機處理器麒麟系列,視頻采集和編解碼處理器系列,無線通信方向芯片等。 目錄 一、視頻行業(yè)1、視頻...
閱讀 1027·2023-01-14 11:38
閱讀 1019·2023-01-14 11:04
閱讀 860·2023-01-14 10:48
閱讀 2301·2023-01-14 10:34
閱讀 1096·2023-01-14 10:24
閱讀 998·2023-01-14 10:18
閱讀 623·2023-01-14 10:09
閱讀 689·2023-01-14 10:02