このコードでは、トラックバーで選択された 1 つの色の円形のオブジェクトを取得し、コーナーを検出して、オブジェクトの周りに円を作成します。このコードでは、トラックバーで選択された色を検出します。
import numpy as np
import cv2
def nothing(x):
pass
#nparray=np.array((0,0), 0)
cv2.namedWindow('image')
B=0
G=0
R=0
b=0
g=0
r=0
# create trackbars for color change
cv2.createTrackbar('r','image',0,255,nothing)
cv2.createTrackbar('g','image',0,255,nothing)
cv2.createTrackbar('b','image',0,255,nothing)
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
web = cv2.VideoCapture(0)
while(1):
base_high = np.array([B, G, R])
base_low = np.array([b, g, r])
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
r = cv2.getTrackbarPos('r', 'image')
g = cv2.getTrackbarPos('g', 'image')
b = cv2.getTrackbarPos('b', 'image')
R = cv2.getTrackbarPos('R', 'image')
G = cv2.getTrackbarPos('G', 'image')
B = cv2.getTrackbarPos('B', 'image')
ret, frame = web.read()
cv2.flip(frame, 3, frame)
hrv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hrv, base_low, base_high)
mask=cv2.erode(mask,None,iterations=2)
mask=cv2.dilate(mask,None,iterations=2)
res = cv2.bitwise_and(frame, frame, mask=mask)
#add next code
frame=cv2.resize(frame,(400,300))
mask=cv2.resize(mask,(400,300))
res=cv2.resize(res,(400,300))
cv2.imshow("original",frame)
cv2.imshow("masked", mask)
cv2.imshow("res", res)
cv2.destroyAllWindows()
その後、このコードを追加すると
cnt = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
centro = None
if len(cnt) > 0:
m = max(cnt, key=cv2.contourArea)
((x, y), r) = cv2.minEnclosingCircle(m)
M = cv2.moments(m)
centro = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
if r > 10:
cv2.circle(res.copy(), (int(x), int(y)), int(r), (0, 255, 255), 2)
それは私にそのエラーを与える
C:\Python27\python.exe C:/Users/MY/OneDrive/trackbar-colorselection/demo.py
OpenCV Error: Assertion failed (lb.type() == ub.type()) in cv::inRange, file C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\core\src\arithm.cpp, line 1984
Traceback (most recent call last):
File "C:/Users/MY/OneDrive/trackbar-colorselection/demo.py", line 41, in <module>
mask = cv2.inRange(hrv, base_low, base_high)
cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\core\src\arithm.cpp:1984: error: (-215) lb.type() == ub.type() in function cv::inRange