Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect a specific line from a image using R

enter image description here

I am new to image processing. I want to detect a specific line in this image, which is the horizontal line in the middle of it. I am wondering how to approach it. This is the map, and it has already been simplified to the edge map.

like image 385
theOnlyihao Avatar asked Oct 22 '25 00:10

theOnlyihao


1 Answers

Here's one method.

Let's start by reading in your image. We'll use the png library for this, so if you don't have it installed, you'll want to install.packages("png") first.

library(png)

img_link <- "https://i.sstatic.net/PygvJ.png"

img <- readPNG(readBin(img_link, "raw", 1e6))

The readPNG function extracts the image as an array. In this case, the array is 360 by 371 by 4:

dim(img)
#> [1] 360 371   4

This means the image is 360 by 371 pixels and contains four channels: red, blue, green and alpha (transparency).

We can plot this array at any time by calling:

plot(as.raster(img))

To find a horizontal red line, all we need to do is look at the row sums of the pixel values in the green channel, which will drop sharply at the target row.

sum_green <- apply(img[,,2], 1, sum)

We can plot this vector to ensure there is a row with a large drop-off in one of the rows, as we would expect.

plot(sum_green, type = "l")

To get this row, we just find the minimum row sum:

target_row <- which.min(sum_green)

target_row
#> [1] 183

So our red line is on the 183rd row. To prove this, let's make the 183rd row of our image black and draw it again:

img[target_row, , 1:3] <- 0

plot(as.raster(img))

This looks correct.

like image 91
Allan Cameron Avatar answered Oct 24 '25 16:10

Allan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!