这里我们提供三种方式,效果各有不同。
编程环境为pycharm。
如要使用该代码,记得注释掉其中的两个方法
# 三种马赛克方式
import cv2
import numpy as np
if __name__ == '__main__':
img = cv2.imread("C:\\Users\\C汪汪\\OneDrive\\桌面\\本机照片\\img.jpeg")
# 输出高度1080、宽度1542和通道数3
print(img.shape)
# 马赛克方式一:效果与我们所认知的马赛克效果有所差异,通过压缩拉伸来让图片失真
# 压缩十倍 宽度,高度
img2 = cv2.resize(img, (154, 108))
# 拉伸十倍
img3 = cv2.resize(img2, (1542, 1080))
cv2.imshow('beauty', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 马赛克方式二:效果比第一种明显好
img2 = cv2.resize(img, (154, 108))
# 按行重复
img3 = np.repeat(img2, 10, axis=0)
# 按列重复
img4 = np.repeat(img3, 10, axis=1)
cv2.imshow('beauty', img4)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 马赛克方式三:伪马赛克
# 每10个中取出一个像素,细节被剥离,图片从而变小
img2 = img[::10, ::10]
cv2.namedWindow('beauty', cv2.WINDOW_NORMAL)
cv2.resizeWindow('beauty', (1542, 1080))
cv2.imshow('beauty', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
# repeat验证
import numpy as np
a = np.array([1, 2, 3])
# 输出结果为[1 1 1 2 2 2 3 3 3],一维
print(np.repeat(a, 3))
b = np.array([[1, 2, 3], [6, 7, 8]])
# 输出结果为:[1 1 1 2 2 2 3 3 3 6 6 6 7 7 7 8 8 8],还是一维,而数据是二维
print(np.repeat(b, 3))
# 输出结果为:
# [[1 2 3]
# [1 2 3]
# [1 2 3]
# [6 7 8]
# [6 7 8]
# [6 7 8]]
print(np.repeat(b, 3, axis=0))
c = np.repeat(b, 3, axis=0)
d = np.repeat(c, 3, axis=1)
# 输出结果为:
# [[1 1 1 2 2 2 3 3 3]
# [1 1 1 2 2 2 3 3 3]
# [1 1 1 2 2 2 3 3 3]
# [6 6 6 7 7 7 8 8 8]
# [6 6 6 7 7 7 8 8 8]
# [6 6 6 7 7 7 8 8 8]]
print(d)
import cv2
import numpy as np
if __name__ == '__main__':
img = cv2.imread("D:\\Python\\OpenCV\\img.jpeg")
# 1.人为定位
# 取出人脸,左上角(514,150),右下角(900,480)
# 2.切片获取人脸
# 注意切割是先高度后宽度
face = img[80:440, 570:900]
# 3.有间隔的切片,重复,再切片,赋值
# 每10个中取出1个像素,若想要马赛克密集一些,则每7个中取1个即可
face = face[::10, ::10]
# 行重复10次
face = np.repeat(face, 10, axis=0)
# 列重复10次
face = np.repeat(face, 10, axis=1)
# 填充,尺寸一致,若是运行报错,则进行尺寸裁剪 face[:高度, :宽度]
img[80:440, 570:900] = face
# 4.显示
cv2.imshow('beauty', img)
cv2.waitKey(0)
cv2.destroyAllWindows()