色の抽出
2015/8/10
Python2.7.6, OpenCV 2.6
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower = np.array([0, 30, 60])
upper = np.array([180, 255, 255])
img_mask = cv2.inRange(hsv, lower, upper)
img = cv2.bitwise_and(img, img, mask=img_mask)
Python3 OpenCV3で指定した色のみを抽出して表示する
https://www.blog.umentu.work/python3-opencv3%E3%81%A7%E6%8C%87%E5%AE%9A%E3%81%97%E3%81%9F%E8%89%B2%E3%81%AE%E3%81%BF%E3%82%92%E6%8A%BD%E5%87%BA%E3%81%97%E3%81%A6%E8%A1%A8%E7%A4%BA%E3%81%99%E3%82%8B%E3%80%90%E5%8B%95%E7%94%BB/
# -*- coding: utf-8 -*-
import cv2
def extract_color( src, h_th_low, h_th_up, s_th, v_th ):
"""
出力画像 extract_color( 入力画像, 色相のしきい値(下), 色相のしきい値(上), 彩度のしきい値, 明度のしきい値 )
http://venuschjp.blogspot.jp/2015/02/pythonopencv.html
"""
hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
if h_th_low > h_th_up:
ret, h_dst_1 = cv2.threshold(h, h_th_low, 255, cv2.THRESH_BINARY)
ret, h_dst_2 = cv2.threshold(h, h_th_up, 255, cv2.THRESH_BINARY_INV)
dst = cv2.bitwise_or(h_dst_1, h_dst_2)
else:
ret, dst = cv2.threshold(h, h_th_low, 255, cv2.THRESH_TOZERO)
ret, dst = cv2.threshold(dst, h_th_up, 255, cv2.THRESH_TOZERO_INV)
ret, dst = cv2.threshold(dst, 0, 255, cv2.THRESH_BINARY)
ret, s_dst = cv2.threshold(s, s_th, 255, cv2.THRESH_BINARY)
ret, v_dst = cv2.threshold(v, v_th, 255, cv2.THRESH_BINARY)
dst = cv2.bitwise_and(dst, s_dst)
dst = cv2.bitwise_and(dst, v_dst)
return dst
if __name__=="__main__":
capture = cv2.VideoCapture(0)
if capture.isOpened() is False:
raise("IO Error")
cv2.namedWindow("Capture", cv2.WINDOW_AUTOSIZE)
cv2.namedWindow("Extract", cv2.WINDOW_AUTOSIZE)
while True:
ret, image = capture.read()
if ret == False:
continue
ext_image = extract_color(image, 330, 10, 50, 100)
cv2.imshow("Capture", image)
cv2.imshow("Extract", ext_image)
if cv2.waitKey(33) >= 0:
cv2.imwrite("image.png", image)
cv2.imwrite("extract_image.png", ext_image)
break
cv2.destroyAllWindows()
def main():
pass
if __name__ == '__main__':
main()
Python版OpenCVで色抽出を行う
http://venuschjp.blogspot.jp/2015/02/pythonopencv.html