'foreground & background separation from image using python and opencv
here I'm doing Soil Height measurement Project using Python & Opencv i am trying to calculate height from fixed bottom line to upper boundary of soil mountains shown in image.
for that purpose i wanted to do foreground & background separation. i tried a lot but didn't work as we want general logic to do that
from the above image i only wanted a Soil Mountains so i can calculate distance & wanted to remove background
error in image not taking top edge of moutain
error in image not taking top edge of moutain

"""
Our operations on the frame come here
"""
frame = img_op.resize_img(frame, (512, 512))
gray = img_op.get_grayscale(frame)
# if i put this it's removing all edges
# i wanted only top edges of the soil
blurred = img_op.GaussianBlur(gray, (5, 5))
mean_of_frame = np.mean(blurred)
min_threshold = 0.66 * mean_of_frame
max_threshold = 1.33 * mean_of_frame
print(f"mean: {mean_of_frame} min_th: {min_threshold} max_th: {max_threshold}")
# Canny = img_op.canny(blurred, 30, 150)
Canny = img_op.canny(blurred, min_threshold, max_threshold)
## To make green, red color to white
x = get_HSV_process_frame(frame)
Canny[x] = 255
no_zero_cnts_x1_y1_th_val = 80
vertical_col = Canny[:, col_no]
# print(list(enumerate(vertical_col)))
""" Get the Cordinates """
try:
x1, y1 = get_x1_y1_cordinate(vertical_col, col_no, no_zero_cnts_x1_y1_th_val)
except Exception as e:
x1, y1 = col_no, 438
print("X1, Y1 Problem", e)
blurr_flag = True
# bottom cordinates are fix
x2, y2 = (col_no, 438)
Logic for getting x1 & y1 is i am searching for white pixel from top once i got white pixel i'm counting black pixel if i got continuous 80 black pixel after white pixel. i'm considering that white pixel as a x1, y1
Solution 1:[1]
A suggestion here is to look at deltas. Between the stair and the background is clear horizontal (ish) break. A transformation to get the light, or hue delta's between pixels (or groups of) in a horizontal direction may find the boundary between that stair and the soil. Cut here to exclude other noise?
A similar trick could be used on the vertical, however, the soil wall to floor transition is subtle, more so than some of the transitions within the soil - so this could only get you part of the way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Danny Staple |
