color_drawing.py and error with img.width()/2

I’m trying to run the color_drawing.py example.
This code runs just fine …

But when I try to modify using that as an example … in order to draw a line from the top of the image in the middle to the bottom of the image in the middle, I get an error “Can not convert float to int”.

# Color Drawing Example
#
# This example shows off your OpenMV Cam's built-in drawing capabilities. This
# example was originally a test but serves as good reference code. Please put
# your IDE into non-JPEG mode to see the best drawing quality.

import sensor, image, time

sensor.reset()
sensor.set_framesize(sensor.QVGA)

# All drawing functions use the same code to pass color.
# So we just need to test one function.

while(True):

    
    # Test Draw Line (RGB565)
    sensor.set_pixformat(sensor.RGB565)
    img = sensor.snapshot()
    width = img.width()*.5
    height = img.height()
    for i in range(img.width()):
        img.draw_line([0,0,width,img.height()])

Any ideas why that the snippet ‘img.width()/2’ works in the example but not in this code?

Python doesn’t convert floats to ints for you. It will upgrade values to floats if a float is used however. Wrap the result in int().

or use double “/”

img.width()//2

Right … but why does it work in the example?
Is the example img.width() parameter somehow already an int?

Yeah… Not sure why. MP issue.

Hi,

You convert width to float by multiplying by 0.5

width = img.width()*.5

And then you pass it to a function that expects an int:

img.draw_line([0,0,width,img.height()])



Any ideas why that the snippet ‘img.width()/2’ works in the example but not in this code?

I don’t see any

img.width()/2

in your code. The problem is width is now a float:

import sensor, image, time

sensor.reset()
sensor.set_framesize(sensor.QVGA)
sensor.set_pixformat(sensor.RGB565)

img = sensor.snapshot()
width = img.width()*.5
height = img.height()
print("width type:", type(width), "height type:", type(height))

Prints:

MicroPython v1.8-4393-gd23b5949 on 2017-06-24; OPENMV3 with STM32F765
Type "help()" for more information.
>>> width type: <class 'float'> height type: <class 'int'>

EDIT/UPDATE:

Note width()/2 will also convert to float. It works in the example, because there’s an int() wrapping the value c

        img.draw_line([i, 0, i, img.height()-1], color = [0, int(c), 0])