0

I have this image, with a white object:

enter image description here

I cut the image and draw a vertical and horizontal line:

enter image description here

and I would like to measure the width and height of white objetc in contact of the lines, vertical and horizontal. But my approach was wrong, I got the total size. Here the results:

w = 453
h = 555

I think this the total size of cutted image. To do this I used this code:

import cv2
import numpy as np

############################################################################

mask_ref = cv2.imread("/original_image.jpg", 0)

hh, ww = mask_ref.shape[:2]

# get the single external contours
contours = cv2.findContours(mask_ref, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

# fixing position

    #print('Angle: ', angle)
if angle < -45 and width > height:
    angle = -(90 + angle)
# otherwise, check width vs height
else:
    if angle > -45 and width > height:
        angle = -(-90 +angle)
    else: 
        angle= -angle

# negate the angle to unrotate
neg_angle = -angle
#print('unrotation angle:', neg_angle)
#print('')

# Get rotation matrix
M = cv2.getRotationMatrix2D(center, neg_angle, scale=1.0)

# unrotate to rectify 
rectified = cv2.warpAffine(mask_ref, M, (ww, hh), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)

# threshold it again to binary
rectified = cv2.threshold(rectified, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# get bounding box of contour of rectified image
cntrs = cv2.findContours(rectified, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
cntr = cntrs[0]
x,y,w,h = cv2.boundingRect(cntr)

# crop to blob limits
crop = rectified[y:y+h, x:x+w]

# get width at every row of crop
count = np.count_nonzero(crop, axis=1)
#### Draw Image Figure
x1, y1 = w, int(h*0.5)
x2, y2 = 1, int(h*0.5)

line_thickness = 2
cv2.line(crop, (x1, y1), (x2, y2), (0, 0, 0), thickness=line_thickness)

# Calculate the center coordinate of the image
center_x, center_y = w // 2, h // 2

# Draw vertical line from top to bottom center
cv2.line(crop, (center_x, 0), (center_x, h), (0, 0, 0), thickness=line_thickness)

print(w)
print(h)

Some suggestion about the code? I really appreciate.

Curious G.
  • 838
  • 8
  • 23
  • 2
    Define "total size"? Why do you think you are getting that? Where is it going wrong? – fmw42 Aug 03 '23 at 15:35
  • 2
    It's not clear to me either what you are actually trying to measure or what the significance is of the lines you have constructed. Please click [edit] and clarify. Thank you. – Mark Setchell Aug 03 '23 at 16:49
  • 1
    Do you want to get the length of those black lines intersecting with your white object ? – Barış Aktaş Aug 04 '23 at 14:10

0 Answers0