代码:
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")
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
img_path = '2inch_blue_1.jpg'
img = cv2.imread(img_path)
im_in = Mark_Color(img, 10)
th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV);
im_floodfill = im_th.copy()
h, w = im_th.shape[:2]
mask = np.zeros((h + 2, w + 2), np.uint8)
cv2.floodFill(im_floodfill, mask, (0, 0), 255);
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
im_out = im_th | im_floodfill_inv
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)
效果: 按照Display依次为:
然后,可以继续设计有趣的应用。
|