網站首頁 編程語言 正文
OpenCV-Python是一個Python庫,旨在解決計算機視覺問題。
OpenCV是一個開源的計算機視覺庫,1999年由英特爾的Gary Bradski啟動。Bradski在訪學過程中注意到,在很多優秀大學的實驗室中,都有非常完備的內部公開的計算機視覺接口。這些接口從一屆學生傳到另一屆學生,對于剛入門的新人來說,使用這些接口比重復造輪子方便多了。這些接口可以讓他們在之前的基礎上更有效地開展工作。OpenCV正是基于為計算機視覺提供通用接口這一目標而被策劃的。
安裝opencv
pip3 install -i https://pypi.doubanio.com/simple/ opencv-python
思路:
1、首先區分三張圖片:
base圖片代表初始化圖片;
template圖片代表需要在大圖中匹配的圖片;
white圖片為需要替換的圖片。
2、然后template圖片逐像素縮小匹配,設定閾值,匹配度到達閾值的圖片,判定為在初始圖片中;否則忽略掉。
3、匹配到最大閾值的地方,返回該區域的位置(x,y)
4、然后用white圖片resize到相應的大小,填補到目標區域。
match函數:
"""檢查模板圖片中是否包含目標圖片"""
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函數:
"""將目標圖片鑲嵌到指定坐標位置"""
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()
每次執行需要初始化x,y(圖片匹配初始位置參數),w,h(圖片縮放初始寬高)
x = 0
y = 0
w = 0
h = 0
flag = True
threshold = 0
template = ''
num_1 = 0
num_2 = 0
photo3 = ''
"""參數初始化"""
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 = ''
"""參數初始化"""
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)
執行結果:
原文鏈接:https://blog.csdn.net/weixin_44784088/article/details/124253179
相關推薦
- 2023-11-12 ubuntu18.04 開機后 USB 端口不能使用;臨時添加usb驅動導致鼠標鍵盤不可用ubunt
- 2023-02-25 C++中vector迭代器失效與深淺拷貝問題詳析_C 語言
- 2022-09-29 C#/VB.NET中從?PDF?文檔中提取所有表格_C#教程
- 2022-06-06 MybatisPlus二級緩存體系探究分析_相關技巧
- 2022-11-06 Django中Migrate和Makemigrations實操詳解_python
- 2022-06-08 SpringCache通用緩存學習
- 2022-05-21 基于C++實現酒店管理系統_C 語言
- 2022-10-30 在C#程序中注入惡意DLL的方法詳解_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支