Home > Blockchain >  Is there any way to calculate the white distance from the image using python opencv
Is there any way to calculate the white distance from the image using python opencv

Time:07-26

As you can see in the image, the size of the image is 2000*2000. We have to find the distance of the image from all the 4 coordinates. I am trying with opencv contours but on some other image it is not working.

image = cv2.imread(image_full_path)
ori_h, ori_w, _ = image.shape
print("Original height, width-->", ori_h, ori_w)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # grayscale
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)  # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
dilated = cv2.dilate(thresh, kernel, iterations=13)  # dilate
contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # get contours

idx = 0
# for each contour found, draw a rectangle around it on original image
# print('length', len(contours))
for contour in contours:
    idx  = 1

    # get rectangle bounding contour
    [x, y, w, h] = cv2.boundingRect(contour)
    remaining_height_bottom = ori_h - (y   h)
    remaining_width_right_side = ori_w - (x   w)

    print("Upper Height, Right Width-->", y, x)
    print("Bottom Height, Left Width-->", remaining_height_bottom, remaining_width_right_side)
    print("Image Height, Image Width-->", h, w)

Image size is 2000 * 2000

Thanks in advance.If anyone thinks that the way of asking questions is wrong please ignore. I really need help.

CodePudding user response:

Please find the code below it working for me

img = cv2.imread(file_full_path) # Read in the image and convert to grayscale
ori_h, ori_w, _ = img.shape
scrollbarright = 20
img = img[:, :-scrollbarright]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = 255*(gray < 128).astype(np.uint8)
coords = cv2.findNonZero(gray)
x, y, w, h = cv2.boundingRect(coords)
print("I am ",x,y,w,h)

remaining_height_bottom = ori_h - (y   h)
remaining_width_right_side = ori_w - (x   w)

print("Upper Height, Right Width-->", y, x)
print("Bottom Height, Left Width-->", remaining_height_bottom, remaining_width_right_side)
print("Image Height, Image Width-->", h, w)
print("Original Image Height,Original Image Width-->", ori_h, ori_w)
  • Related