Opencv 馬賽克和毛玻璃效果與圖片融合的實現

1.馬賽克效果

馬賽克的基本原理就是,用某一個區域的某一個像素點替代這個區域所有的像素點,從而導致圖片出現模糊的效果,如下:

import cv2


# 馬賽克效果
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
flag = 2   # 系數,系數越小,馬賽克的效果越不明顯
for m in range(26,height):
    for n in range(140,880):
        if m%flag==0 and n%flag==0:
            for i in range(0,flag):
                for j in range(0,flag):
                    (b,g,r) = img[m,n]
                    img[i+m,j+n] = (b,g,r)

cv2.imshow('dst',img)
cv2.waitKey(0)

2. 毛玻璃效果

import cv2
import numpy as np
import random

# 毛玻璃效果
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(height-8):
    for j in range(width-8):
        index = int(random.random()*8)  # 生成0-8之間的隨機數(不包括8)
        dst[i, j] = img[i+index,j+index]
cv2.imshow('dst',dst)
cv2.waitKey(0)

3. 圖片的融合

就是將兩張圖片融合到一張圖片上,即可看到第一張圖片的效果,也可以看到第二張圖片的效果。

import cv2

img_1 = cv2.imread(filename='../anqila21.jpg',flags=1)
img_2 = cv2.imread(filename='../huanghe.jpg',flags=1)
imgInfo = img_1.shape
height = imgInfo[0]
width = imgInfo[1]
# roi
roi = 0.5
dst = cv2.addWeighted(img_1,roi,img_2,(1-roi),0)
cv2.imshow('dst',dst)
cv2.waitKey(0)

算法實現

import cv2
import numpy as np

img_1 = cv2.imread(filename='../anqila21.jpg',flags=1)
img_2 = cv2.imread(filename='../huanghe.jpg',flags=1)
imgInfo = img_1.shape
height = imgInfo[0]
width = imgInfo[1]
# roi
roi = 0.5
dst = np.zeros((height,width,3),np.uint8)

for i in range(height):
    for j in range(width):
        (b1,g1,r1) = img_1[i,j]
        (b2,g2,r2) = img_2[i,j]
        dst[i,j] = (int(b1*roi+b2*(1-roi)),int(g1*roi+g2*(1-roi)),int(r1*roi+r2*(1-roi)))

cv2.imshow('dst',dst)
cv2.waitKey(0)

以上就是Opencv 馬賽克和毛玻璃效果與圖片融合的實現的詳細內容,更多關於Opencv 的資料請關註WalkonNet其它相關文章!

推薦閱讀: