使用OpenCV从背景裁剪图像(条带提取)

2024-04-28 19:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用OpenCv从下图中提取焊盘部分。 从这样的图像开始: strip with background

我正试图将其提取到如下图像中:

enter image description here

以这样的形象结束

enter image description here

我目前有以下几点

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('strip.png')

grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresholded = cv2.threshold(grayscale, 0, 255, cv2.THRESH_OTSU)
bbox = cv2.boundingRect(thresholded)
x, y, w, h = bbox
foreground = img[y:y+h, x:x+w]

cv2.imwrite("output.png", foreground)

哪个输出:

enter image description here


Tags: 图像importnumpyimgpngasnpcv2
1条回答
网友
1楼 · 发布于 2024-04-28 19:49:33

如果你仔细观察图像的上下部分,它看起来更杂乱,而中间部分(这是你想要的输出)看起来柔软平滑

由于中心部分是均匀的,平滑过滤器(如侵蚀)不会对该部分产生太大的影响,否则上部会发生明显的变化

在第一步,我用一个简单的阈值去除黑色背景。此外,我对图像进行了一些平滑处理,计算结果与原始图像之间的差异,然后对最终结果进行阈值化以去除不需要的像素

然后我做了一些形态学处理来去除过程中残留的噪声。最后,在boundingRect命令的帮助下,我提取了所需的线段(白色轮廓):

删除背景:

enter image description here

侵蚀模糊后的差异图像:

enter image description here

打开过程后的差异图像和阈值:

enter image description here

最后是白色对象的边界框:

enter image description here

我编写的代码(C++opencv):

Mat im = imread("E:/t.jpg", 0);
resize(im, im, Size() , 0.3, 0.3); // # resizing just for better visualization

Mat im1,im2, im3;

// Removing the black background:
threshold(im, im1, 50, 255, THRESH_BINARY);
vector<vector<Point>> contours_1;
findContours(im1, contours_1, RETR_CCOMP, CHAIN_APPROX_NONE);

Rect r = boundingRect(contours_1[0]);

im(r).copyTo(im);
im.copyTo(im3);

imshow("background removed", im); 

// detecting the cluttered parts and cut them:
erode(im, im2, Mat::ones(3, 3, CV_8U), Point(-1, -1), 3);

im2.convertTo(im2, CV_32F);
im3.convertTo(im3, CV_32F);
subtract(im2, im3, im1);

double min, max;
minMaxIdx(im1, &min, &max);
im1 = 255*(im1 - min) / (max - min);
im1.convertTo(im1, CV_8U);

imshow("the difference image", im1);

threshold(im1, im1, 250, 255, THRESH_BINARY);

erode(im1, im1, Mat::ones(3, 3, CV_8U), Point(-1, -1), 3);
dilate(im1, im1, Mat::ones(3, 3, CV_8U), Point(-1, -1), 7);

imshow("the difference image thresholded", im1);

vector<Point> idx, hull;
vector<vector<Point>> hullis;
findNonZero(im1, idx);
Rect rr = boundingRect(idx);

rectangle(im, rr, Scalar(255, 255, 255), 2);

imshow("Final segmentation", im);

waitKey(0);

相关问题 更多 >