opencv-面部模糊

# 使用OpenCV和Python模糊和匿名化面孔
import numpy as np
import cv2
import argparse

def anonymize_face_simple(image, factor=3.0):
    # 根據模糊內核的大小自動確定
    # 在輸入圖像的空間尺寸上
    (h, w) = image.shape[:2]
    kW = int(w / factor)
    kH = int(h / factor)
    # 確保內核的寬度爲奇數
    if kW % 2 == 0:
        kW -= 1
    # 確保內核的高度爲奇數
    if kH % 2 == 0:
        kH -= 1
    # 使用我們的計算結果將高斯模糊應用於輸入圖像
    # 內核大小
    return cv2.GaussianBlur(image, (kW, kH), 0)

def anonymize_face_pixelate(image, blocks=3):
    # 將輸入圖像劃分爲NxN個塊
    (h, w) = image.shape[:2]
    xSteps = np.linspace(0, w, blocks + 1, dtype="int")
    ySteps = np.linspace(0, h, blocks + 1, dtype="int")
    # 在x和y方向上循環遍歷塊
    for i in range(1, len(ySteps)):
        for j in range(1, len(xSteps)):
            # 計算開始和結束(x,y)座標
            # 當前塊
            startX = xSteps[j - 1]
            startY = ySteps[i - 1]
            endX = xSteps[j]
            endY = ySteps[i]
            # 使用NumPy數組切片提取ROI,計算
            # ROI的均值,然後用
            # 表示原始圖像中ROI上的RGB值
            roi = image[startY:endY, startX:endX]
            (B, G, R) = [int(x) for x in cv2.mean(roi)[:3]]
            cv2.rectangle(image, (startX, startY), (endX, endY),
                (B, G, R), -1)
    # 返回像素化的模糊圖像
    return image

# 構造參數解析並解析參數
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str, default="examples/demo.jpg",
    help="圖片地址")
ap.add_argument("-m", "--method", type=str, default="simple",
    choices=["simple", "pixelated"],
    help="人臉模糊/匿名方法")
ap.add_argument("-b", "--blocks", type=int, default=20,
    help="# 像素化模糊方法的塊數")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
    help="過濾弱檢測的最小概率")
args = vars(ap.parse_args())


# 從磁盤加載序列化的面部檢測器模型
prototxtPath = "deploy.prototxt"
weightsPath = "res10_300x300_ssd_iter_140000.caffemodel"
net = cv2.dnn.readNet(prototxtPath, weightsPath)
# 從磁盤加載輸入圖像,對其進行克隆,然後在空間上獲取圖像
image = cv2.imread(args["image"])
orig = image.copy()
(h, w) = image.shape[:2]

# 構造圖像斑點
blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),
    (104.0, 177.0, 123.0))

# 獲得面部位置
net.setInput(blob)
detections = net.forward()

# 循環位置
for i in range(0, detections.shape[2]):
    # 提取與相關聯的置信度(即概率)
    confidence = detections[0, 0, i, 2]
    # 通過確保更大的置信度來濾除弱檢測
    if confidence > args["confidence"]:
        # 計算邊界框的(x,y)座標
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        (startX, startY, endX, endY) = box.astype("int")
        # 提取面部ROI
        face = image[startY:endY, startX:endX]
        
        # 模糊方法選擇
        if args["method"] == "simple":
            face = anonymize_face_simple(face, factor=3.0)
        else:
            face = anonymize_face_pixelate(face,
                blocks=args["blocks"])
        # 將模糊的臉存儲在輸出圖像中
        image[startY:endY, startX:endX] = face


# 顯示原始圖像和帶有模糊圖像的輸出圖像
output = np.hstack([orig, image])
cv2.imshow("Output", output)
cv2.waitKey(0)

效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章