当你有很多文件需要遮盖住关键信息的时候,虽然说可以手动马赛克,但是如果文件数太多的话就很麻烦了。一方面会有遗漏,另外一方面会工作量大,定位也确实麻烦。
而且还有一点很重要,这样打码最安全,其他各种打码方案,包括你平常看到的各种马赛克方案存在被破解的可能!你可以认为是平常打码的最安全方案。
例如我20页文件有40多个需要马赛克的地方,操作起来很麻烦,也不美观;所以从实际需要出发写了这段代码,个人是相当满意。
下面代码用来获取你要打码的部分,选中后按回车,自动生成随机文件到指定目录
import numpy as np
import cv2
import time
import hashlib
img=cv2.imread('c:/opencv/wps/20210208_2.jpg')
img_gary=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.namedWindow('select', 0)
cv2.resizeWindow('select', 700, 900)
while True:
r=cv2.selectROI('select', img,False)
# 没有任何选择的情况下退出
if r[2]==0 :break
imgselect=img[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]
imgselect=cv2.cvtColor(imgselect, cv2.COLOR_BGR2GRAY)
m=hashlib.md5()
m.update(bytes(str(time.time()),encoding='utf-8'))
cv2.imwrite('c:/opencv/filter/'+str(m.hexdigest())+'.jpg',imgselect)
h,w=imgselect.shape[:2]
res=cv2.matchTemplate(img_gary, imgselect , cv2.TM_CCOEFF_NORMED)
per=0.8
loc=np.where(res>=per )
i=0
for pt in zip(*loc[::-1 ]):
bottom_right=(pt[0]+w,pt[1]+h)
cv2.rectangle(img, pt, bottom_right, (255,255,0),-1)
cv2.waitKey(0)
cv2.destroyAllWindows()
下面的代码用于自动过滤,哈哈哈
import numpy as np
import cv2
import os
# 欲处理的文件夹
sourpath='c:/opencv/wps/'
# 欲过滤的图片文件夹
filterpath='c:/opencv/filter/'
# 处理过后保存的文件夹
targetpath='c:/opencv/wps2/'
spath=os.listdir(sourpath)
for f in spath:
filename=sourpath+f
img=cv2.imread(filename)
img_gary=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(filename)
filterfiles=os.listdir(filterpath)
per=0.7
for childfilter in filterfiles:
filterfilename=filterpath+childfilter
imgfilter=cv2.imread(filterfilename,0)
h,w=imgfilter.shape[:2]
res=cv2.matchTemplate(img_gary, imgfilter , cv2.TM_CCOEFF_NORMED)
loc=np.where(res>=per )
for pt in zip(*loc[::-1 ]):
bottom_right=(pt[0]+w,pt[1]+h)
cv2.rectangle(img, pt, bottom_right, (0,0,0),-1)
cv2.imwrite(targetpath+f, img)
例如我可能在上面的处理后得到下面的图片:
更自由,更灵活,不用手工摸码,也可以有选择性。
这是俺写的比较有成就感的代码之一,哈哈哈哈哈