I have an image, of shape [1024, 1024, 3] in a reduced color space (like ~100 colors). I need to count, for every possible couple of colors, how many times one appears in the neighborhood of the other. This is quite simple in python, the problem I have is to write it using Tensorflow functions. I will make a simple example to make it easier to understand:
Let`s consider a color space with only 4 colors (named 1,2,3,4) and a 4x4 image:
[ [2 4 1 4]
[2 4 2 1]
[2 4 3 1]
[2 1 1 2] ]
From this I have to compute the neighborhood color histogram, that explain what is written above: how many pixel of every color appears in the neighborhood of every pixel of every other color. The NCH of the above image is the following:
[ [8 7 4 6]
[7 6 2 12]
[4 2 0 2]
[6 12 2 4] ]
To make it clear, the 8 in the first row means that color 1 appears in the neighborhoods of color 1 8 times. The 7 indicates that color 2 appears in the neighborhoods of color 1 7 times and so on.
In this simple example I consider a neighborhood of size 3x3, but the code I am working on should be extendable to a generic NxN size.
The only step I was able to implement with Tensorflow is to split each image in the batch (I am implementing this as the first step of a loss function, so it has to work with batches) in NxN patches, centered on every pixel, using the following function:
patches = tf.image.extract_patches(image, sizes=(1, D_size, D_size, 1), strides=(1, 1, 1, 1),
padding='SAME', rates=[1, 1, 1, 1])
What I have to do now is to iterate over every patch and increment, according to the central color of the patch, the NCH matrix. This is very simple using loops, but I struggle to find the right Tensorflow functions to execute them in a more parallel way.
I am pretty new to the tensorflow world, so I understand it may seems an obvious question, but I really do not know what else to try and I will prefer to not use loops. Thank you all in advance.