title: Python: Calculating the angle between two bones in an x-ray
body: <p>I am trying to write a script to calculate the angle between two bones given an x-ray. </p>
  
  <p>A sample x-ray would look like the following: </p>
  
  <p><a href="https://i.stack.imgur.com/KeLgW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KeLgW.jpg" alt="Sample x-ray"></a></p>
  
  <p>I am trying to calculate the midline of each bone, essentially a line following the midpoints of the two sides of a bone, and then compare the angle between the two midlines.</p>
  
  <p>I have tried using OpenCV to get the outline of the bones, but it does not seem accurate enough and gets lots of extra data. I am stuck on how to move next and how I would calculate the midline. I am quite new to image processing but have experience with Python.</p>
  
  <p>Getting edges using OpenCV results:</p>
  
  <p><a href="https://i.stack.imgur.com/eReBi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eReBi.png" alt="enter image description here"></a></p>
  
  <p>Code for OpenCV:</p>
  
  <pre><code>import cv2
  
  # Load the image
  img = cv2.imread("xray-3.jpg")
  
  # Find the contours
  imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  edges = cv2.Canny(img,60,200)
  im2, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  
  hierarchy = hierarchy[0] # get the actual inner list of hierarchy descriptions
  
  # For each contour, find the bounding rectangle and draw it
  cv2.drawContours(img, contours, -1, (0,255,0), 3)
  
  # Finally show the image
  cv2.imshow('img',img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  </code></pre>