Python with OpenCV in Colab for Color Detection and find Corner Detection

Jetnipat Thankeatphangan
2 min readSep 18, 2019

--

Import libs

import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
from google.colab import drive

Read image and Show

img_path = ‘/content/gdrive/My Drive/Medium’
img = cv2.imread(os.path.join(img_path,’imagename.jpg’))
plt.imshow(img)
plt.show()

Convert BGR to HSV

hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
plt.imshow(hsv)
plt.show()

Set Range HSV of Target and draw contours

กำหนดช่วงสีที่เราต้องการกัน

lower_green = np.array([119,27,45]) 
upper_green = np.array([208,255,255])
mask = cv2.inRange(hsv,lower_green,upper_green)
img2, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,contours,-1,(0,255,0),10)
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
plt.show()

Create contours of image

img2, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
n = len(contours)
for i in range(0,n):
cnt = contours[i]
per = cv2.arcLength(cnt,True)
print('per = %.0f'%(per))
if per > 4145:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),20)
plt.axis("off")
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
plt.show()
################## perMAX = 4145 ##################

--

--

No responses yet