3 python opencv image image-processing
我正在使用 Opencv 和 python 来检测形状然后裁剪它们。我已经成功地做到了这一点,但是现在我正在尝试拍摄裁剪后的图像并删除它们的背景。
图像内部有一个圆圈,周围环绕着灰色。(它可以是灰色的,也可以是不止一种颜色)。
如何删除圆形边框(黑色)周围的颜色 - 我们可以将灰色转换为黑色 - 作为边框颜色,甚至完全删除它并使其透明。
结果图像应仅包含圆圈。
至少在这个图像中,不需要检测圆圈 use houghCircle)
。我认为threshold
它和find the inner contour
,然后make mask
和do bitwise-op
就可以了!
我的步骤:
(1)读取并转换为灰色
(2) findContours
(3) 找到较小的轮廓,创建一个蒙版
(4)做
bitwise_and
以crop
这是我的结果:
#!/usr/bin/python3
# 2018.01.20 20:58:12 CST
# 2018.01.20 21:24:29 CST
import cv2
import numpy as np
## (1) Read
img = cv2.imread("img04.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
## (2) Threshold
th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
## (3) Find the min-area contour
_cnts = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnts = sorted(cnts, key=cv2.contourArea)
for cnt in cnts:
if cv2.contourArea(cnt) > 100:
break
## (4) Create mask and do bitwise-op
mask = np.zeros(img.shape[:2],np.uint8)
cv2.drawContours(mask, [cnt],-1, 255, -1)
dst = cv2.bitwise_and(img, img, mask=mask)
## Save it
cv2.imwrite("dst.png", dst)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26296 次 |
最近记录: |