Coin counting
ภาพตัวอย่าง

step 1 : เปิด terminal (windows - cmd , mac - terminal)
step 2 : เข้าโฟลเดอร์ที่ติดตั้ง Visual environment และไลบารี่ OpenCV
$ cd opencv
step 3 : เปิด Visual environment
## windows
$ <C:path\your\project>\env\Scripts\activate.bat
## ubuntu & mac
$ source venv/bin/activate
step 4 : command “code .” in terminal

step 5 : create file counter.py
step 6 : ลำดับการทำงานของชุดคำสั่ง
นับเฉพาะเหรียญ หมายความว่า ต้องทำการแยกวัตถุกับภาพพื้นหลังออกจากกัน ก็คือใช้ Threshold แต่เนื่องจาก Threshold ต้องใช้กับภาพไบนารีหรือภาพสีเทาเท่านั้น หลังจากได้ภาพไบนารีที่มีแต่เหรียญได้แล้ว จากนั้นจึงทำการวาดกรอบรอบเหรียญเพื่อทำการนับ หรือก็คือการใช้ Contour
รับภาพ
cv2.imread
เปลี่ยนภาพเป็นสีเทา
cv2.cvtColor
เบลอภาพเพื่อลด noise
cv2.GaussianBlur
threshold
cv2.threshold
contour
cv2.findContour & cv2.drawContours
แสดงเลขตรงจุดกึ่งกลางของเหรียญ
cv2.moment & cv2.putText
step 7 : save file and run "python counter.py" on terminal

Example:
import cv2
import imutils
image = cv2.imread("path/your/image.jpg")
image = imutils.resize(image,width=500)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(3,3),7)
T,thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY)
cv2.imshow("threshold",thresh)
cnts = cv2.findContours(thresh,cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
clone = image.copy()
i = 0
for c in cnts:
# compute the area and the perimeter of the contour
area = cv2.contourArea(c)
if area > 0:
i = i+1
cv2.drawContours(clone, [c], -1, (0, 255, 0), 2)
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.putText(clone, "#{}".format(i), (cX - 20, cY), cv2.FONT_HERSHEY_SIMPLEX,
1.25, (255, 255, 255), 4)
else:
pass
cv2.imshow("original",image)
cv2.imshow("counter",clone)
cv2.waitKey(0)

Last updated
Was this helpful?