Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JFrame
- import org.bytedeco.javacv.{CanvasFrame, OpenCVFrameConverter}
- import org.bytedeco.javacpp.opencv_core, opencv_core._
- import org.bytedeco.javacpp.opencv_imgcodecs._
- import org.bytedeco.javacpp.opencv_imgproc._
- import java.io.File
- import java.util.Random
- object Main extends App {
- def reduceRect(r: Rect, n: Int = 2): List[Rect] = {
- if (r.width > (r.height * 1.15)) {
- val w = r.width / n
- if (w > (r.height * 1.15))
- reduceRect(r, n+1)
- else
- (0 until n).map { i =>
- new Rect(r.x + (i * w) + 1, r.y, w - 2, r.height)
- }.toList
- } else r :: Nil
- }
- val img = imread(new File(
- getClass.getClassLoader.getResource("10_1_pull.png").toURI).getAbsolutePath)
- if (img.empty())
- sys.error("Empty!!!")
- val erodeKernel = getStructuringElement(MORPH_ELLIPSE, new Size(48,48))
- val gray = new Mat
- cvtColor(img, gray, CV_BGR2GRAY)
- val copy = new Mat
- gray.copyTo(copy)
- threshold(gray, gray, 37, 255, 0)
- dilate(gray, gray, erodeKernel)
- erode(gray, gray, erodeKernel)
- val mask = new Mat(gray.rows, gray.cols, CV_8UC1)
- val rectmask = new Mat(gray.rows, gray.cols, CV_8UC1)
- val rectmask1 = new Mat(gray.rows, gray.cols, CV_8UC1)
- val contours = new MatVector
- val hierarchy = new Mat
- val bottom = 0.85
- val top = 0.29
- val nohigher = img.rows * top
- val nolower = img.rows * bottom
- val WHITE = new Scalar(255,255,255,0)
- val BLACK = new Scalar(0,0,0,0)
- findContours(gray, contours,
- CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, new Point(0, 0))
- val r = new Random
- (0 until contours.size.toInt) foreach { c =>
- val rect = boundingRect(contours.get(c))
- val area = contourArea(contours.get(c))
- if (rect.y + rect.height < nolower && rect.y > nohigher && area > 10000) {
- reduceRect(rect) foreach { r1 =>
- val color = new Scalar(r.nextInt(255), r.nextInt(255), r.nextInt(255), 0)
- if (rectmask.isNull) {
- rectmask.zero()
- rectmask1.zero()
- }
- rectangle(img, r1, WHITE, 8, LINE_8, 0)
- rectangle(rectmask, r1, WHITE, FILLED, LINE_8, 0)
- bitwise_not(rectmask, rectmask1)
- // drawContours(img, contours, c, color, FILLED, LINE_8, hierarchy, 0, new Point)
- drawContours(rectmask1, contours, c, WHITE, FILLED, LINE_8, hierarchy, 0, new Point)
- rectmask.copyTo(mask, rectmask1)
- rectangle(mask, r1, WHITE, 8, LINE_8, 0)
- }
- }
- }
- val masked = new Mat
- img.copyTo(masked, mask)
- val canvas = new CanvasFrame("My Image", 1)
- canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
- val converter = new OpenCVFrameConverter.ToMat()
- val out = converter.convert(masked)
- canvas.setCanvasSize(out.imageWidth / 4, out.imageHeight / 4)
- canvas.showImage(out)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement