代码:
import cv2
import numpy as np
#标记特定颜色区域
def Mark_Color(img, flag_color):
#自定义
if flag_color ==0:
lower = np.array([24, 43, 46], dtype="uint8")
upper = np.array([43, 255, 255], dtype="uint8")
#黑色
elif flag_color ==1:
lower = np.array([0, 0, 0], dtype="uint8")
upper = np.array([180, 255, 46], dtype="uint8")
# 灰色
elif flag_color == 2:
lower = np.array([0, 0, 46], dtype="uint8")
upper = np.array([180, 43, 220], dtype="uint8")
# 白色
elif flag_color == 3:
lower = np.array([0, 0, 221], dtype="uint8")
upper = np.array([180, 30, 255], dtype="uint8")
# 红色
elif flag_color == 4:
lower = np.array([156, 43, 46], dtype="uint8")
upper = np.array([180, 255, 255], dtype="uint8")
# 红色2
elif flag_color == 5:
lower = np.array([0, 43, 46], dtype="uint8")
upper = np.array([10, 255, 255], dtype="uint8")
# 橙色
elif flag_color == 6:
lower = np.array([11, 43, 46], dtype="uint8")
upper = np.array([25, 255, 255], dtype="uint8")
# 黄色
elif flag_color == 7:
lower = np.array([26, 43, 46], dtype="uint8")
upper = np.array([34, 255, 255], dtype="uint8")
# 绿色
elif flag_color == 8:
lower = np.array([35, 43, 46], dtype="uint8")
upper = np.array([77, 255, 255], dtype="uint8")
# 青色
elif flag_color == 9:
lower = np.array([78, 43, 46], dtype="uint8")
upper = np.array([99, 255, 255], dtype="uint8")
# 蓝色
elif flag_color == 10:
lower = np.array([100, 43, 46], dtype="uint8")
upper = np.array([124, 255, 255], dtype="uint8")
# 紫色
else:
lower = np.array([125, 43, 46], dtype="uint8")
upper = np.array([155, 255, 255], dtype="uint8")
converted = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
markingMask = cv2.inRange(converted, lower, upper)
return markingMask
# markingMask = cv2.GaussianBlur(markingMask, (5, 5), 0)
# marked_img = cv2.bitwise_and(img, img, mask=markingMask)
# return marked_img
# Read image
# im_in = cv2.imread("2inch_blue_1.jpg", cv2.IMREAD_GRAYSCALE);
img_path = '2inch_blue_1.jpg'
img = cv2.imread(img_path)
# 分离背景(背景为白色,人物为黑色)
im_in = Mark_Color(img, 10)
# Threshold.
# Set values equal to or above 220 to 0.
# Set values below 220 to 255.
th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV);
# Copy the thresholded image.
im_floodfill = im_th.copy()
# Mask used to flood filling.
# Notice the size needs to be 2 pixels than the image.
h, w = im_th.shape[:2]
mask = np.zeros((h + 2, w + 2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0, 0), 255);
# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
# Combine the two images to get the foreground.
im_out = im_th | im_floodfill_inv
# Display images.
cv2.imshow("Thresholded Image", im_th)
cv2.imshow("Floodfilled Image", im_floodfill)
cv2.imshow("Inverted Floodfilled Image", im_floodfill_inv)
cv2.imshow("Foreground", im_out)
cv2.waitKey(0)