Copy $ cv2.inRange(image, lower, upper)
Copy import numpy as np
import cv2
image = cv2.imread("path/your/image.jpg")
colors = [
([17, 15, 100], [50, 56, 200]),
([86, 31, 4], [220, 88, 50]),
([25, 146, 190], [62, 174, 250]),
([103, 86, 65], [145, 133, 128])
]
for (lower, upper) in colors:
lower = np.array(lower, dtype = "uint8")
upper = np.array(upper, dtype = "uint8")
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
cv2.imshow("images", np.hstack([image, output]))
cv2.waitKey(0)
tracking จะเป็นเทคนิคที่ใช้ในการติดตามวัตถุที่อยู่บนภาพวิดีโอหรือการแสดงภาพแบบ Real-time โดยในหัวข้อนี้จะเป็นการติดตามวัตถุที่มีสีตามที่ผู้ใช้กำหนด
Copy import imutils
import cv2
camera = cv2.VideoCapture(0)
colorRanges = [
((29, 86, 6), (64, 255, 255), "green"),
((57, 68, 0), (151, 255, 255), "blue")]
while True:
(grabbed, frame) = camera.read()
frame = imutils.resize(frame, width=600)
blurred = cv2.GaussianBlur(frame, (11, 11), 0)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
for (lower, upper, colorName) in colorRanges:
mask = cv2.inRange(hsv, lower, upper)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
(cX, cY) = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
if radius > 10:
cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
cv2.putText(frame, colorName, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
1.0, (0, 255, 255), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
camera.release()
cv2.destroyAllWindows()