Title: Let the user straighten images with vertical lines in Python
This example provides a small improvement to the example Let the user interactively straighten images in Python. That example let you draw a line on an image to show the horizontal direction on that image, but some images are more naturally straightened vertically. For example, the Leaning Tower of Pisa is relatively tall and thin so it's easier to draw its vertical edges than its horizontal edges. This example lets you straighten by drawing either a horizontal or vertical image.
Converting Vertical Angles
The change needed to the previous example is extremely simple. Here's the program's mouse_up event handler with the new code highlighted in blue.
def mouse_up(self, event):
'''Finish drawing.'''
if self.new_line is None: return
# Calculate the line's angle. -180 < new_angle <= 180.
dx = self.end_point[0] - self.start_point[0]
dy = self.end_point[1] - self.start_point[1]
new_angle = math.degrees(math.atan2(dy, dx))
# See whether the new angle is closer to vertical than horizontal.
if abs(new_angle) > 45:
# Convert it into a horizontal angle.
new_angle -= 90
# Subtract this angle from the total angle so far.
self.angle += new_angle
self.show_image()
# Delete the orientation line.
self.canvas.delete(self.new_line)
self.start_point = self.end_point = self.new_line = None
The math.atan2 function returns an angle between -180° and 180°. (Or really between -π/2 and π/2 radians.) If the angle is vertical-ish, then the angle is either greater than 45° or less than -45°.
If the angle is vertical, the code subtracts 90 degrees to convert it into an equivalent horizontal angle.
The code then proceeds as before. That's all there is to it!
Conclusion
One quick modification allowed the original example to handle both vertical and horizontal orientation lines. The program is pretty usable at this point, but my next two posts will make a few other small modifications to make the program even more robust.
Download the example to experiment with it and to see additional details.
|