我可以在互联网上找到的是opencv 2.x java代码示例。我正在使用opencv 3.2并尝试加载图像并将所有长度超过x像素的黑线变为白色(删除它们)。这是我从一个opencv 2.4版本的hough变换示例开始的地方......
Mat img = Imgcodecs.imread("C:/Users/user1/Desktop/topdown-6.jpg");
// Mat img = Imgcodecs.imread(fileName)
// generate gray scale and blur
Mat gray = new Mat();
Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY);
Imgproc.blur(gray, gray, new Size(3, 3));
// detect the edges
Mat edges = new Mat();
int lowThreshold = 50;
int ratio = 3;
Imgproc.Canny(gray, edges, lowThreshold, lowThreshold * ratio);
Mat lines = new Mat();
Imgproc.HoughLinesP(edges, lines, 1, Math.PI / 180, 50, 50, 10);
for(int i = 0; i < lines.cols(); i++) {
double[] val = lines.get(0, i);
Imgproc.line(img, new Point(val[0], val[1]), new Point(val[2], val[3]), new Scalar(0, 0, 255), 2);
}
Image edgesImg = toBufferedImage(edges);
Image linesImg = toBufferedImage(lines);
Image imgg = toBufferedImage(img);
我收到了错误
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file
C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\color.cpp, line 9748
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
]
at org.opencv.imgproc.Imgproc.cvtColor_1(Native Method)
at org.opencv.imgproc.Imgproc.cvtColor(Imgproc.java:1778)
at Main.main(Main.java:174)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
对我的目标的任何帮助都会很棒。我应该使用opencv版本2.x吗?
编辑:
public Image toBufferedImage(Mat m){
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels()*m.cols()*m.rows();
byte [] b = new byte[bufferSize];
m.get(0,0,b); // ERROR HAPPENING HERE
BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
答案 0 :(得分:1)
问题是您要将图像加载为灰度,因此以后无需转换。 cvtColor希望在进行BGR2GRAY
时,输入mat在你的情况下是一个颜色Mat