在 opencv 中创建用户定义的阈值

making a user defined threshold in opencv

我正在尝试使用 this 建议的算法检测皮肤。
为此,我只需要采用属于此类别的像素: conditions

我可以通过“手动”遍历图像的每个像素并使用 if 语句来实现。
有没有一种方法可以使用(最好)opencv 或 numpy 来更有效地做到这一点?

您可以通过以下方式进行:

import cv2
import numpy as np
from pathlib import PosixPath

RED_MIN, RED_MAX = 20, 200
BLUE_MIN, BLUE_MAX = 20, 200
GREEN_MIN, GREEN_MAX = 20, 200

if __name__ == '__main__':
    # 1) Load the image
    p = PosixPath('../../Pictures/Spring.jpeg')
    img = cv2.imread(str(p))
    cv2.imshow('Spring', img)

    # 2) Split the image into Blue, Green and Red channels
    # (remember, in OpenCV the channels' order is BGR and not RGB)
    blue_img = img[:, :, 0]
    green_img = img[:, :, 1]
    red_img = img[:, :, 2]

    # 3) Create masks for each color range
    blue_mask = cv2.inRange(blue_img, BLUE_MIN, BLUE_MAX)
    blue_mask[np.where(blue_mask == 255)] = 1

    green_mask = cv2.inRange(green_img, GREEN_MIN, GREEN_MAX)
    green_mask[np.where(green_mask == 255)] = 1

    red_mask = cv2.inRange(red_img, RED_MIN, RED_MAX)
    red_mask[np.where(red_mask == 255)] = 1

    # 4) Combine the relevant image pixels into one final image
    filtered_img = np.zeros_like(img)
    filtered_img[:, :, 0] = blue_img * blue_mask
    filtered_img[:, :, 1] = green_img * green_mask
    filtered_img[:, :, 2] = red_img * red_mask

    cv2.imshow('Filtered image', filtered_img)

    cv2.waitKey()
    cv2.destroyAllWindows()

干杯。