Exemplo n.º 1
0
def spatial_filter(img, kernel, dxy=None):
    """ Convolves `img` with `kernel` assuming a stride of 1. If `img` is linear,
     `dxy` needs to hold the dimensions of the image.
  """
    # Make sure that the image is 2D
    _img = np.array(img)
    if dxy is None:
        dx, dy = _img.shape()
        isInt = type(img[0:0])
        isFlat = False
    else:
        dx, dy = dxy
        if dx * dy != _img.size():
            raise TypeError("Dimensions do not match number of `img` elements")
        isInt = type(img[0])
        isFlat = True
    img2d = _img.reshape((dx, dy))

    # Check if kernel is a square matrix with an odd number of elements per row
    # and column
    krn = np.array(kernel)
    dk, dk2 = krn.shape()
    if dk != dk2 or dk % 2 == 0 or dk <= 1:
        raise TypeError(
            "`kernel` is not a square 2D matrix or does not have an "
            "odd number of row / column elements")

    # Make a padded copy of the image; pad with mean of image to reduce edge
    # effects
    padd = dk // 2
    img2dp = np.ones((dx + padd * 2, dy + padd * 2)) * numerical.mean(img2d)
    img2dp[padd:dx + padd, padd:dy + padd] = img2d
    imgRes = np.zeros(img2dp.shape())

    # Convolve padded image with kernel
    for x in range(0, dx):
        for y in range(0, dy):
            imgRes[x + padd, y + padd] = numerical.sum(
                img2dp[x:x + dk, y:y + dk] * krn[:, :])

    # Remove padding, flatten and restore value type if needed
    _img = imgRes[padd:dx + padd, padd:dy + padd]
    if isFlat:
        _img = _img.flatten()
    if isInt:
        _img = list(np.array(_img, dtype=np.int16))
    return _img
Exemplo n.º 2
0
                # EdgComp code
                loop = True
                initialtimems = utime.ticks_ms()
                while loop:
                    for i in range(NUM_ADC_READINGS):
                        Vplus3V3 = adcVplus.read() * (3.3 / 4095)
                        Vplus5V = (Vplus3V3 * (R1left + R2left)) / R2left
                        Vref3V3 = adcVref.read() * (3.3 / 4095)
                        Vref5V = (Vref3V3 * (R1right + R2right)) / R2right
                        try:
                            BnTlist[i] = ((Vplus5V - Vref5V) * 125000) / Vref5V
                        except ZeroDivisionError:
                            continue

                    timems = utime.ticks_diff(utime.ticks_ms(), initialtimems)
                    BnTmean = numerical.mean(BnTlist)
                    utime.sleep(TIME_MEASURE)
                    BnTstdev = numerical.std(BnTlist)

                    log.write("{}, {}, {}\n".format(BnTmean, BnTstdev,
                                                    timems // 1000))
                    message_counter += 1

                    if message_counter == NUM_MEASURES:
                        log.close()
                        break

        if ure.search('GET /flc100.csv', line):
            isDownload = True

    cl.close()
Exemplo n.º 3
0
def find_blobs(img, dxy, nsd=1.0):
    """ Detect continues area(s) ("blobs") with pixels above a certain
      threshold in an image. `img` contains the flattened image (1D),
      `dxy` image width and height, and `nsd` a factor to calculate the blob
      threshold from image mean and s.d. (thres = avg +sd *nsd).
  """
    # Initialize
    blobs = []
    for i in range(MAX_BLOBS):
        blobs.append(blob_struct())
    nBlobs = 0
    posList = []

    # Extract the parameters
    dx, dy = dxy
    n = dx * dy

    # Copy image data into a float array
    pImg = np.array(img)

    # Calculate mean and sd across (filtered) image to determine threshold
    avg = numerical.mean(pImg)
    sd = numerical.std(pImg)
    thres = avg + sd * nsd

    # Find blob(s) ...
    #
    # Mark all pixels above a threshold
    pPrb = (pImg - avg) / sd
    pMsk = np.array(pImg >= thres, dtype=np.uint8) * 255
    nThres = int(numerical.sum(pMsk) / 255)

    # Check if these above-threshold pixels represent continuous blobs
    nLeft = nThres
    iBlob = 0
    while nLeft > 0 and iBlob < MAX_BLOBS:
        # As long as unassigned mask pixels are left, find the next one using
        # `ulab.numerical.argmax()`, which returns the index of the (first)
        # hightest value, which should be 255
        iPix = numerical.argmax(pMsk)
        x = iPix % dx
        y = iPix // dx

        # Unassigned pixel found ...
        posList.append((x, y))
        pMsk[x + y * dx] = iBlob
        nFound = 1
        bx = float(x)
        by = float(y)
        bp = pPrb[x + y * dx]

        # Find all unassigned pixels in the neighborhood of this seed pixel
        while len(posList) > 0:
            x0, y0 = posList.pop()
            for k in range(4):
                x1 = x0 + xoffs[k]
                y1 = y0 + yoffs[k]
                if ((x1 >= 0) and (x1 < dx) and (y1 >= 0) and (y1 < dy)
                        and (pMsk[int(x1 + y1 * dx)] == 255)):
                    # Add new position from which to explore
                    posList.append((x1, y1))
                    pMsk[int(x1 + y1 * dx)] = iBlob
                    nFound += 1
                    bx += float(x1)
                    by += float(y1)
                    bp += pPrb[int(x1 + y1 * dx)]
        # Update number of unassigned pixels
        nLeft -= nFound

        # Store blob properties (area, center of gravity, etc.); make sure that
        # the blob list remaines sorted by area
        k = 0
        if iBlob > 0:
            while (k < iBlob) and (blobs[k].area > nFound):
                k += 1
            if k < iBlob:
                blobs.insert(k, blob_struct())
        blobs[k].ID = iBlob
        blobs[k].area = nFound
        blobs[k].x = by / nFound
        blobs[k].y = bx / nFound
        blobs[k].prob = bp / nFound
        iBlob += 1
    nBlobs = iBlob

    # Copy blobs into list as function result
    tempL = []
    for i in range(nBlobs):
        if blobs[i].area > 0:
            tempL.append(blobs[i].as_list)

    # Return list of blobs, otherwise empty list
    return tempL
Exemplo n.º 4
0
                lst_Temp.append(mlx.Read_MLX90615_Temperatures())
                count += 1
                print('Carregando ...')
                if (count == NUM_TEMP_MEASURE):
                    break
            else:
                lst_Tambient.append(mlx.Read_MLX90615_Temperatures())

    if (count == NUM_TEMP_MEASURE) and (not flag_exit):
        lst_object = [i[0] / 100 for i in lst_Temp]
        lst_ambient = [i[0] / 100 for i in lst_Tambient]

        lst_Tobject = list(zip(
            lst_object,
            lst_ambient))  # lista de tuplas (temp do objeto, temp do ambiente)
        obj_mean = numerical.mean(
            lst_object)  # indica a média da temperatura da pessoa/objeto
        obj_std = numerical.std(lst_object)  # desvio padrão

    if (count == NUM_TEMP_MEASURE) and (not flag_exit):

        pyb.LED(2).on()
        watchmen = 0
        for i in lst_object:
            if (obj_mean - obj_std <= i <= obj_mean + obj_std):
                watchmen += 1
                if watchmen == NUM_TEMP_MEASURE:
                    print('\nMedida feita!')
        if watchmen != NUM_TEMP_MEASURE:
            pyb.LED(2).off()
            pyb.LED(1).on()
            print('\nVocê pode ter se afastado ...')
Exemplo n.º 5
0
# Ulab is a numpy-like module for micropython, meant to simplify and speed up common
# mathematical operations on arrays. This basic example shows mean/std on an image.
#
# NOTE: ndarrays cause the heap to be fragmented easily. If you run out of memory,
# there's not much that can be done about it, lowering the resolution might help.

import sensor, image, time, ulab as np
from ulab import numerical

sensor.reset()                          # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE)  # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)      # Set frame size to QVGA (320x240)
clock = time.clock()                    # Create a clock object to track the FPS.

while (True):
    img = sensor.snapshot()         # Take a picture and return the image.
    a = np.array(img, dtype=np.uint8)
    print("mean: %d std:%d"%(numerical.mean(a), numerical.std(a)))
Exemplo n.º 6
0
    color = (0xFF, 0x00, 0xF0)
    blk_space = (blk_size // 4)
    for i in range(0, int(round(level / 10))):
        fb.draw_rectangle(SIZE + offset,
                          SIZE - ((i + 1) * blk_size) + blk_space, 20,
                          blk_size - blk_space, color, 1, True)


while (True):
    if (raw_buf != None):
        pcm_buf = np.array(array.array('h', raw_buf))
        raw_buf = None

        if CHANNELS == 1:
            fft_buf = extras.spectrogram(pcm_buf)
            l_lvl = int((numerical.mean(abs(pcm_buf)) / 32768) * 100)
        else:
            fft_buf = extras.spectrogram(pcm_buf[0::2])
            l_lvl = int((numerical.mean(abs(pcm_buf[1::2])) / 32768) * 100)
            r_lvl = int((numerical.mean(abs(pcm_buf[0::2])) / 32768) * 100)

        fb.clear()
        draw_fft(fb, fft_buf)

        draw_audio_bar(fb, l_lvl, 0)
        if CHANNELS == 2:
            draw_audio_bar(fb, r_lvl, 25)
        fb.flush()

# Stop streaming
audio.stop_streaming()