I am starting to work with openCV and python in a project related with stereovision. I found this page of documentation about the Census Transform in C++ with openCV. link
Does anyone know if there are similar functions for python implementation?
(e.g. cv2.nameofthefunction)
Thank you all!
EDIT: the excellent solution of PM 2Ring (thank you again) can work with openCV with this little change: instead of using Image.open
img = cv2.imread(img.png)
#some minor changes I needed like select some ROI and store them in img2[j]
#then a for cycle in which I wrote
src_img = img2[j]
h, w = src_img.shape
where the "shape" instruction seems to switch the order of w and h compared to "size" command. Then I paste the rest of the code of PM 2Ring and it worked wonderfully
I don't use openCV, and I don't know if there's an existing implementation of the Census Transform. However, it's easy enough to implement using Numpy.
Here's a simple demo that uses PIL to handle loading the image and converting the array data back to an image.
#!/usr/bin/env python
''' The Census Transform
Scan an 8 bit greyscale image with a 3x3 window
At each scan position create an 8 bit number by comparing the value
of the centre pixel in the 3x3 window with that of its 8 neighbours.
The bit is set to 1 if the outer pixel >= the centre pixel
See http://stackoverflow.com/questions/38265364/census-transform-in-python-opencv
Written by PM 2Ring 2016.07.09
'''
import numpy as np
from PIL import Image
iname = 'Glasses0S.png'
oname = 'Glasses0S_census.png'
#Get the source image
src_img = Image.open(iname)
src_img.show()
w, h = src_img.size
print('image size: %d x %d = %d' % (w, h, w * h))
print('image mode:', src_img.mode)
#Convert image to Numpy array
src_bytes = np.asarray(src_img)
#Initialize output array
census = np.zeros((h-2, w-2), dtype='uint8')
#centre pixels, which are offset by (1, 1)
cp = src_bytes[1:h-1, 1:w-1]
#offsets of non-central pixels
offsets = [(u, v) for v in range(3) for u in range(3) if not u == 1 == v]
#Do the pixel comparisons
for u,v in offsets:
census = (census << 1) | (src_bytes[v:v+h-2, u:u+w-2] >= cp)
#Convert transformed data to image
out_img = Image.fromarray(census)
out_img.show()
out_img.save(oname)
source
output
The original full-colour Glasses image was created by Gilles Tran using POV-Ray, and is in the public domain. It may be found on Wikipedia.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With