การ contours โดยใช้ python colab

PimDeed
1 min readSep 19, 2019

--

เริ่มจากการ import cv และ os

from matplotlib import pyplot as plt
import cv2
import os

from google.colab import drive
drive.mount(‘/content/gdrive’)

import numpy as np

และimport รูปภาพ

image_path = “/content/gdrive/My Drive/Image”
img2 = cv2.imread(os.path.join(image_path,’ww.jpg’),cv2.IMREAD_COLOR)

ต่อมาเป็นการแสดงรูปออกเป็นแบบขาวดำ โดยกำหนดค่าสี ว่าให้สีที่ต้องการกลายเป็นขาวดำ

img2 = img2[:,:,::-1]
plt.imshow(img2)
plt.show()

hsv = cv2.cvtColor(img2,cv2.COLOR_BGR2HSV)
lower_pink = np.array([79,101,118])
upper_pink = np.array([175,255,255])
plt.imshow(hsv)
plt.show()
mask=cv2.inRange(hsv,lower_pink,upper_pink)
plt.imshow(mask)
plt.show()

gray=cv2.cvtColor(mask,cv2.COLOR_GRAY2RGB)
plt.imshow(gray)
plt.show()

ต่อมาการหาว่ามีคอนทัวร์ทั้งหมดกี่จุด

img2, contours, hierarch = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
n = len(contours)

print(‘There are %d contours’%n)

และทำการคอนทัวร์

cv2.drawContours(img2, contours, -1(0,0,255),10)

plt.axis(“off”)
plt.imshow(cv2.cvtColor(img2,cv2.COLOR_BGR1RGB))
plt.show()

cv2.drawContours(img, contours, -1, (0,0,255),10)

plt.axis(“off”)
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BRG2RGB))
plt.show()

ต่อมาเป็นการหาว่าคอนทัวร์ทุกจุดที่มีมีค่าเท่าไหร่บ้าง

for i in range(0,n):
cnt = contours[i]
perimeter = cv2.arcLength(cnt,True)
print(‘cnt %2d perimeter is %.0f’%(i,perimeter))

และเลือกคอนทัวร์เฉพาะจุดที่สนใจ ในที่นี้คือจุดที่ค่าสูงสุด

for i in range(0,n):
cnt = contours[i]
perimeter = cv2.arcLength(cnt,True)

if perimeter>2000:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img2,(x,y),(x+w,y+h),(0,255,0),10)

plt.axis(“off”)
plt.imshow(cv2.cvtColor(img2,cv2.COLOR_BGR2RGB))
plt.show()

--

--