fvid/fvid/fvid_cython.pyx

45 lines
1.5 KiB
Cython
Raw Normal View History

2020-10-17 17:33:12 +02:00
# distutils: language=c
2020-10-13 14:15:56 +02:00
# cython: boundscheck=False
# cython: cdivision=True
# cython: wraparound=False
2020-10-17 17:33:12 +02:00
cpdef cy_get_bits_from_image(image):
2020-10-13 14:15:56 +02:00
cdef int width, height, x, y
cdef str pixel_bin_rep
2020-10-17 17:33:12 +02:00
cdef (int, int, int) pixel, white_diff, black_diff
cdef (bint, bint, bint) truth_tuple
2020-10-13 14:15:56 +02:00
width, height = image.size
px = image.load()
bits = ""
for y in range(height):
for x in range(width):
pixel = px[x, y]
2020-10-17 17:33:12 +02:00
pixel_bin_rep = <str>"0"
2020-10-13 14:15:56 +02:00
2020-10-17 17:33:12 +02:00
# for exact matches, indexing each pixel individually is faster in cython for some reason
2020-10-13 14:15:56 +02:00
if pixel[0] == 255 and pixel[1] == 255 and pixel[2] == 255:
2020-10-17 17:33:12 +02:00
pixel_bin_rep = <str>"1"
2020-10-13 14:15:56 +02:00
elif pixel[0] == 0 and pixel[1] == 0 and pixel[2] == 0:
2020-10-17 17:33:12 +02:00
pixel_bin_rep = <str>"0"
2020-10-13 14:15:56 +02:00
else:
white_diff = (abs(pixel[0] - 255), abs(pixel[1] - 255), abs(pixel[2] - 255))
# min_diff = white_diff
black_diff = (abs(pixel[0] - 0), abs(pixel[1] - 0), abs(pixel[2] - 0))
# if the white difference is smaller, that means the pixel is closer
# to white, otherwise, the pixel must be black
2020-10-17 17:33:12 +02:00
truth_tuple = (white_diff[0] < black_diff[0], white_diff[1] < black_diff[1], white_diff[2] < black_diff[2])
if all(truth_tuple):
pixel_bin_rep = <str>"1"
2020-10-13 14:15:56 +02:00
else:
2020-10-17 17:33:12 +02:00
pixel_bin_rep = <str>"0"
2020-10-13 14:15:56 +02:00
# adding bits
bits += pixel_bin_rep
return bits