# Find Line Segments Changed for pin drop Pi
#
# This example shows off how to find line segments in the image. For each line object
# found in the image a line object is returned which includes the line's rotation.

# find_line_segments() finds finite length lines (but is slow).
# Use find_line_segments() to find non-infinite lines (and is fast).

enable_lens_corr = True # turn on for straighter lines...

import sensor, image, time

sensor.reset()
sensor.set_pixformat(sensor.RGB565) # grayscale is faster
sensor.set_framesize(sensor.QQVGA)  #160w x 120h
sensor.skip_frames(time = 2000)
clock = time.clock()
pinsTot = 0
crossTot = 0


# All lines also have `x1()`, `y1()`, `x2()`, and `y2()` methods to get their end-points
# and a `line()` method to get all the above as one 4 value tuple for `draw_line()`.

while(True):
    pins = 0
    cross = 0
    clock.tick()
    img = sensor.snapshot()
    if enable_lens_corr: img.lens_corr(1.8) # for 2.8mm lens...

    # `merge_distance` controls the merging of nearby lines. At 0 (the default), no
    # merging is done. At 1, any line 1 pixel away from another is merged... and so
    # on as you increase this value. You may wish to merge lines as line segment
    # detection produces a lot of line segment results.

    # `max_theta_diff` controls the maximum amount of rotation difference between
    # any two lines about to be merged. The default setting allows for 15 degrees.

    for pin in img.find_line_segments(merge_distance = 2, max_theta_diff = 0):
        img.draw_line(pin.line(), color = (255, 0, 0))
        pins = pins + 1
        #print(pin)
# see if this segment crosses imaginary line
        vert = 0
        p1 = pin.x1()
        p2 = pin.x2()
        while vert < 160:
            vert = vert + 15
            if (p1 < vert and p2 >= vert) or (p2 < vert and p1 >= vert):
                cross = cross +1


    pinLen = 10
    Pie = (2 * pinLen * pins) / (15 * cross)
    pinsTot = pinsTot + pins
    crossTot = crossTot + cross
    PieAvg = (2 * pinLen * pinsTot) / (15 * crossTot)
    print(pins, cross, Pie, PieAvg)
