Reference:
#-------------------hsv_RED1.py
import numpy as np
import cv2
def ptext(img1,s,pos,sz):
img2=cv2.putText(img=img1,text=s,org=pos,
fontFace = cv2.FONT_HERSHEY_DUPLEX,
fontScale=sz,color=(125,246,55),thickness=1)
return img2
FW=open('red_A.txt','w')
img=np.zeros((200,600,3),dtype=np.uint8)
for j in range(5):
fl='red_'+str(j)+'.png'
B=50; G=10+20*j; R=200
bgr=np.array([B,G,R], dtype=np.uint8)
img[:,:]=bgr
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
a=str(j)+' '+str(bgr)+' '+str(hsv[0,0,:])
img2=ptext(img,a,(30,30),1.0)
print(a); FW.write(a+'\n')
cv2.imshow('img2',img2)
cv2.imwrite(fl,img)
cv2.waitKey(0)
FW.close()
#-------------------hsv_RED2.py
#使用cv2.inRange函數鎖定特定顏色的區間,獲得顏色的遮罩(面具mask),
#再使用cv2.bitwise_and函數呈現只有mask鎖定區域內(有特定顏色)的圖像
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)
ret,img=cap.read()
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255])
mask1 = cv2.inRange(hsv, lower_red, upper_red)
lower_red = np.array([170, 50, 50])
upper_red = np.array([180, 255, 255])
mask2 = cv2.inRange(hsv, lower_red, upper_red)
mask = mask1 + mask2
red_only = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow('Original Image', img)
cv2.imshow('Red Only', red_only)
cv2.waitKey(0)
cv2.destroyAllWindows()
cap.release()