mee*_*mee 5 python opencv image image-processing
我是 OpenCV 的新手。我想从图像中提取主要对象。因此,我在图像上应用了 Canny 以获取主要对象周围的边缘并得到以下输出:
这是在 Python 中使用 OpenCV 获取此信息的代码:
img = cv2.imread(file)
cv2.imshow("orig", img)
cv2.waitKey(0)
img = cv2.blur(img,(2,2))
gray_seg = cv2.Canny(img, 0, 50)
Run Code Online (Sandbox Code Playgroud)
现在,我想在只获取图像中的主要对象后将下面的图像作为最终输出:
我想以优化的方式进行,因为我必须处理超过 250 万张图像。谁能帮我这个?
如您所见clean canny edge
,要裁剪矩形区域,您应该计算rectangle boundary
.
步骤:
结果:
要计算精明的区域边界,您只需找到非零点,然后得到min-max coords
. 使用 NumPy 很容易实现。然后使用切片操作进行裁剪。
#!/usr/bin/python3
# 2018.01.20 15:18:36 CST
#!/usr/bin/python3
# 2018.01.20 15:18:36 CST
import cv2
import numpy as np
#img = cv2.imread("test.png")
img = cv2.imread("img02.png")
blurred = cv2.blur(img, (3,3))
canny = cv2.Canny(blurred, 50, 200)
## find the non-zero min-max coords of canny
pts = np.argwhere(canny>0)
y1,x1 = pts.min(axis=0)
y2,x2 = pts.max(axis=0)
## crop the region
cropped = img[y1:y2, x1:x2]
cv2.imwrite("cropped.png", cropped)
tagged = cv2.rectangle(img.copy(), (x1,y1), (x2,y2), (0,255,0), 3, cv2.LINE_AA)
cv2.imshow("tagged", tagged)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)
当然,做boundingRect
点工作也是如此。
rect 函数应该提供您需要的功能。下面是如何使用它的示例。
cv::Mat image(img);
cv::Rect myROI(posX, posY, sizeX, sizeY);
cv::Mat croppedImage = image(myROI);
Run Code Online (Sandbox Code Playgroud)
这是用 C++ 编写的,但应该能够找到等效的 Python 代码。
下面的链接提供了更多信息 如何在 OpenCV 中裁剪 CvMat?