# 硬幣找輪廓
# 橢圓+灰階
```python
import cv2
import numpy as np
from numpy import array, uint8
def findcontour(img: np.ndarray):
cv2.threshold(img, dst=img, *(89, 255, 0)) #(圖片,參數為最小門檻值,參數最大門檻值).threshold只能灰階 #檢測輪廓
cv2.morphologyEx(img, dst=img, *(2, array([[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]], dtype=uint8)), iterations=6)
cv2.erode(img, dst=img, *(array([[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]], dtype=uint8),), iterations=1) #腐蝕
cv2.dilate(img, dst=img, *(array([[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]], dtype=uint8),), **{'iterations': 8}) #膨脹
return img
if __name__ == '__main__':
img = cv2.imread("n2.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #圖像從RGB轉到HSV夜色空間(HSV 表示hue、saturation、value)
#img_gray1 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
blurred = cv2.GaussianBlur(img_gray, (11, 11), 0)
binaryIMG = cv2.Canny(blurred, 20, 160)
#cv2.imwrite("9hsvgg_10.jpg",img_gray)
img_copy = img_gray.copy()
process = findcontour(img_gray)
process = cv2.Canny(process, 200, 255, apertureSize=5) #邊緣檢測
if "3.0" < cv2.__version__ < "3.5":
_, cnts, hierarchy = cv2.findContours(process, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) #cv2.RETR_EXTERNAL只取外層的Contour。
else:
cnts, hierarchy = cv2.findContours(process, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# cv2.drawContours(img, cnts, -1, (0, 255, 0), 3) #綠邊界 #繪製所有輪廓-1,其餘參數是顏色,厚度ETC #cnts為所有Contours
for c in cnts:
if cv2.contourArea(c) < 600: #輪廓面積
continue
M = cv2.moments(c)
Cx = int(M["m10"] / M["m00"]) #M['m00']表示輪廓面積
Cy = int(M["m01"] / M["m00"])
cv2.circle(img, (Cx, Cy), 10, (1, 227, 254), -1) #最小外接圓
ellipse = cv2.fitEllipse(c) #橢圓
cv2.ellipse(img, ellipse, (0, 255, 0), 10) #橢圓
mask = np.zeros(img_gray.shape, dtype="uint8") #依Contours圖形建立mask
#mask = np.zeros(img_gray1.shape, dtype="uint8") #依Contours圖形建立mask
#mask = cv2.inRange(img_gray1,(224, 16, 55), (25, 255, 255))
cv2.drawContours(mask, [c], -1, 255, -1) # 255→白色, -1→塗滿
# show the images
#cv2.imshow("1hsv_10.jpg", img) #顯示原圖(有加線)
# cv2.imwrite("1_HSV.jpg",img_gray1)
cv2.imwrite("2hsvg_11.jpg",img)
cv2.imwrite("2hsvg_m_11.jpg",mask)
#cv2.imshow("Image1 + Mask", cv2.bitwise_and(img, img, mask=mask)) #顯示疊起來的圖
cv2.imwrite("2hsvg_bitwise_11.jpg", cv2.bitwise_and(img, img, mask=mask)) # 寫入圖檔
# 按下任意鍵則關閉所有視窗
cv2.waitKey(0)
cv2.destroyAllWindows()