导航菜单
首页 » 问答 » 正文

给图片打马赛克的原理(算法)是怎样的?

emmm,马赛克的目的是为了让人无法辨认原图的区域,只要能满足目的就能用,来几个思路:

大方块

确实可以按题主的思路,划定小方格,让方格里所有像素去平均值,不过算起来有点累,可以直接让一个小方格(如8x8)的像素值都等于小方格里第一个像素,下面是示例代码:

import cv2 as cv
import numpy as np
lena = cv.imread('./lena.jpg')
offset = 8
for row in range(190,240):
    for col in range(180,280):
        if row % offset == 0 and col % offset == 0:
            color = lena[row,col]
            for i in range(offset):
                for j in range(offset):
                    lena[row+i,col+j] = color
cv.imshow('dst',lena)
cv.waitKey(0)

毛玻璃效果

还可以把像素随机被周围像素替换,制造“毛玻璃”效果,原理类似下图

示例代码:

import random
import cv2 as cv
import numpy as np
lena = cv.imread('./lena.jpg')
height,width = lena.shape[0:2]
dst = np.zeros(lena.shape,np.uint8)
offset = 5
for row in range(height): ##
    for col in range(width):
        # radom value
        indexrow = random.randint(0,offset)
        indexcol = random.randint(0, offset)
        randomRow = row + indexrow
        randomCol = col + indexcol
        if randomRow > height - 1:
            randomRow = height - indexrow
        if randomCol > height - 1:
            randomCol = height - indexcol
        dst[row,col] = lena[randomRow,randomCol]
cv.imshow('dst',dst)
cv.waitKey(0)

简单粗暴

如果让我做打码,识别出打码区域,直接把图像值换成一个固定的颜色、固定的图片或随机的颜色,本来就不想让人看,那还要啥自行车啊

import cv2 as cv
import numpy as np
lena = cv.imread('./lena.jpg')
for row in range(190,240):
    for col in range(180,280):
        lena[row,col] = [255,255,255]
cv.imshow('dst',lena)
cv.waitKey(0)

评论(0)

二维码