/** * 价签矫正 */ public void getContouresPic (Bitmap source) { Mat imageSobleOutThreshold = new Mat(); Mat gray = new Mat(); Utils.bitmapToMat(source, imageSobleOutThreshold); Imgproc.cvtColor(imageSobleOutThreshold, imageSobleOutThreshold, Imgproc.COLOR_BGR2GRAY); Imgproc.threshold(imageSobleOutThreshold, gray, 125, 225, Imgproc.THRESH_BINARY);//maxVal就是控制黑白反转的,0是黑 //Utils.matToBitmap(gray, source); ArrayList<RotatedRect> rects = new ArrayList<RotatedRect>(); ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(gray, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); for(int i=0;i<contours.size();i++){ Rect rect = Imgproc.boundingRect(contours.get(i)); if (rect.width > 500 && rect.width/rect.height == 1) { MatOfPoint2f mp2f = new MatOfPoint2f(contours.get(i).toArray()); RotatedRect mr = Imgproc.minAreaRect(mp2f); double area = Math.abs(Imgproc.contourArea(mp2f)); double angle = mr.angle+90; Mat ratationedImg = new Mat(gray.rows(), gray.cols(), CvType.CV_8UC3); ratationedImg.setTo(new Scalar(0, 0, 0)); Point center = mr.center;//中心点 Mat m2 = Imgproc.getRotationMatrix2D(center, angle, 1); Imgproc.warpAffine(imageSobleOutThreshold, ratationedImg, m2, imageSobleOutThreshold.size(), 1, 0, new Scalar(0) );//仿射变换 Utils.matToBitmap(ratationedImg, source); File file = new File(Environment.getExternalStorageDirectory()+"/AiLingGong/", "ll"+System.currentTimeMillis()+".jpg"); try { FileOutputStream out = new FileOutputStream(file); source.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("----------------", "旋转角度是:"+angle+"------"+"-----"+mr); } } }