大致思路如下
对应的方法如下
COLOR_BGR2GRAY
处理,高斯滤波GaussianBlur
处理。canny
算子进行边缘查找,并使用findContours
方法提取边缘坐标点。boundingRect
方法找出硬币所在的矩形进行裁切,使用minEnclosingCircle
找出包络圆作为蒙版,并使用bitwise_and
隐藏背景。首先导入必要的库,测试一下是否加载成功,注意cv2.waitKey(0)
一定不要忘记!
import cv2
import numpy as np
image = cv2.imread("coins.png")
cv2.imshow("if imread successfully",image)
cv2.waitKey(0)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray,(11,11),0)
cv2.imshow("blurred",blurred)
cv2.waitKey(0)
edged = cv2.Canny(blurred, 30, 150)
cv2.imshow("edged",edged)
cv2.waitKey(0)
# 注意这里只能返回2个变量
(cnts,_) = cv2.findContours(edged.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
print(" {} coins in the image".format(len(cnts)))
显示:9 coins in the image
然后画在原图中
coins = image.copy()
cv2.drawContours(coins, cnts, -1, (0,255,0), 2)
cv2.imshow("coins",coins)
cv2.waitKey(0)
coins = image.copy()
cv2.drawContours(coins, cnts, -1, (0,255,0), 2)
cv2.imshow("coins",coins)
cv2.waitKey(0)
for (i,circle) in enumerate(cnts):
# circle是每个提取出来的圆
(x,y,w,h) = cv2.boundingRect(circle)
print("coin #{}".format(i+1))
coin_canvas = image[y:y+h, x:x+w]
cv2.imshow("coin",coin_canvas)
cv2.waitKey(0)
mask = np.zeros(image.shape[:2], dtype = 'uint8')
((centerX,centerY),radius) = cv2.minEnclosingCircle(circle)
# 在蒙版上画圆,这里是灰度图,所以255表示白色
cv2.circle(mask,(int(centerX),int(centerY)), int(radius), 255, -1)
mask = mask[y:y+h, x:x+w]
# 自身和自身进行与运算即可
cv2.imshow("masked coin",cv2.bitwise_and(coin_canvas, coin_canvas, mask = mask))
cv2.waitKey(0)