附上的是图像。我能够摆脱边界上的背景区域,但是图像中的背景区域仍然是持久的。是否有任何方法可以去除图像中的小背景区域。谢谢。
发布于 2015-10-14 10:26:41
对于这样的问题有一个简单的解决办法,基本思想是在RGB颜色空间中分割图像,以过滤掉图像中留下的黑色部分,可以简单地实现如下:
import cv2
import numpy as np
ornament_image = cv2.imread("/Users/anmoluppal/Desktop/outputs/ornament.jpg")
#Considering the black range of background pixels
thresh = cv2.inRange(ornament_image, np.array([0, 0, 0]), np.array([55, 55, 55]))
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cv2.drawContours(ornament_image, contours, -1, (255,255,255), -1)
#Replace the contours with the white color same as the background
但是,这就去掉了点缀图像中的一些非常小的黑色部分,为了保存这些部分,我们可以根据等高线区域对这些部分进行排序,从而过滤掉一些轮廓。
thresh = cv2.inRange(ornament_image, np.array([0, 0, 0]), np.array([55, 55, 55]))
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours = sorted(contours, key = cv2.contourArea, reverse = True)[:len(contours)/20]
cv2.drawContours(ornament_image, contours, -1, (255,255,255), -1)
注意:这种方法也可以保留一些黑色的背景噪声。
进一步改进:
发布于 2015-10-16 05:27:55
以上代码在c++和手动掩码中添加。
#include <iostream>
#include "opencv2/opencv.hpp"
#include <stdio.h>
using namespace std;
using namespace cv;
Mat thresh, hierarchy;
void onMouse( int event, int x, int y, int flags, void* imgptr ){
if ( flags == (EVENT_FLAG_CTRLKEY + EVENT_FLAG_LBUTTON) ) //Sure Background - Red
{
Mat & img = (*(Mat*)imgptr); // first cast, then deref
Point pt1 = Point(x, y);
circle(img, pt1, 7, Scalar(0,0,255), -1, 8);
imshow("Mark Image", img);
waitKey(1);
}
}
int main ()
{
int i =0;
Mat src = imread("C:/Users/Dell/Desktop/computervisionproject/segmentation/segmentation/Final_window.jpg",1);
Mat image = src.clone();
namedWindow("Mark Image",WINDOW_NORMAL);
setMouseCallback("Mark Image",onMouse, &image);
imshow("Mark Image",image);
while(1){
char c=waitKey();
if(c=='s'){
inRange(image, cv::Scalar(0, 0, 0), cv::Scalar(55, 55, 55), thresh);
std::vector<std::vector<cv::Point> > contours;
findContours(thresh,contours, hierarchy, CV_RETR_TREE ,CV_CHAIN_APPROX_NONE);
//findContours(thresh,contours, CV_RETR_TREE ,CV_CHAIN_APPROX_NONE);
cout <<"Hello"<<endl;
drawContours(src, contours, -1, Scalar(255,255,255), -1);
namedWindow( "Display window", WINDOW_NORMAL );
imshow( "Display window", src);
}
}
waitKey();
return 0;
}
https://stackoverflow.com/questions/33117974
复制相似问题