我在Android Studio中使用OpenCV。
我有一张白色背景和黑色区域的图像。在黑色区域,我有一些轮廓。我想检测黑色区域内的轮廓,如下所示:
但是我的代码没有用;相反,它将整个图像的边返回为轮廓:
我做错了什么?
public Mat[] Smudge_detection(Mat color_mat)
{
Mat lab_mat=new Mat();
Imgproc.cvtColor(color_mat, lab_mat, Imgproc.COLOR_RGB2Lab);
List<Mat> lab_list = new ArrayList(3);
Core.split(lab_mat, lab_list);
Mat eqHist=new Mat();
Imgproc.equalizeHist(lab_list.get(0),eqHist);
lab_list.set(0,eqHist);
Core.merge(lab_list,lab_mat);
Mat rgb_mat=new Mat();
Mat gray_mat=new Mat();
Imgproc.cvtColor(lab_mat,rgb_mat,Imgproc.COLOR_Lab2RGB);
Imgproc.cvtColor(rgb_mat,gray_mat,Imgproc.COLOR_RGB2GRAY);
MatOfInt histSize = new MatOfInt(256);
MatOfInt channels=new MatOfInt(0);
Mat hist_ = new Mat();
MatOfFloat histRange = new MatOfFloat(0, 220);
List<Mat>gray_lst= new ArrayList<Mat>(1);
Core.split(gray_mat,gray_lst);
Imgproc.calcHist(gray_lst,channels,new Mat(),hist_,histSize,histRange,false);
Core.MinMaxLocResult mml= Core.minMaxLoc(hist_);
double tresh=mml.maxLoc.y;
// for remove white area around of black circle
Mat thresh_mat=new Mat();
Imgproc.threshold(gray_mat,thresh_mat,tresh,220,THRESH_BINARY);
Mat notmat=new Mat();
Core.bitwise_not(thresh_mat,notmat);
Mat morph_mat=new Mat();
Imgproc.morphologyEx(notmat,morph_mat,Imgproc.MORPH_CLOSE, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(2,2)));
List<MatOfPoint> contours=new ArrayList<>();
final Mat hierarchy = new Mat();
Imgproc.findContours(morph_mat,contours,hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
Mat drawmat=color_mat.clone();
Imgproc.drawContours(drawmat,contours,0,new Scalar(255,50,180),15);
Mat[] out=new Mat[2];
out[0]=contours.get(0);
out[1]=drawmat.clone();
return out;
}
答案 0 :(得分:0)
我在python中的结果,您可以参考:
这是我的python代码:
#!/usr/bin/python3
# 2017.10.08 21:48:13 CST
import cv2
import numpy as np
img = cv2.imread("t.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
retval, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
_,contours,h = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
dst1 = img.copy()
dst2 = img.copy()
cv2.drawContours(dst1, contours, -1, (0,255,0), 3)
cnts = []
for cnt in contours:
rect = cv2.boundingRect(cnt)
x,y,w,h = rect
if w < 10 or h < 10 >>w > 100 or h > 100:
continue
cnts.append(cnt)
print(len(cnts))
cv2.drawContours(dst2, cnts, -1, (0,255,0), 3)
res = np.hstack((dst1, dst2))
cv2.imwrite("res.png", res)
cv2.imshow("res", res)
cv2.waitKey()
cv2.destroyAllWindows()