pceccon
pceccon

Reputation: 9844

Colormap - Python / Matplotlib

I'm doing some image processing, applying some filters, such as the sobel operator, to find edges. So, after applying the operator, I do this:

def classify_edges(magnitude, threshold=.75):
        """
        Classifies a pixel as edge or not based on its magnitude, which is generated after the appliance of an operator
        :param magnitude : the gradient magnitude of the pixel
        :return : the pixel classification
        """
        classification = Dt.Data()
        e = 0
        n = 0
        for x, y in product(range(classification.rows), range(classification.cols)):
            # Not edge
            if magnitude[x][y] > threshold:
                classification.data[x][y] = 1.0
                n += 1
            # Edge
            else:
                classification.data[x][y] = 0.0
                e += 1
        print e, n
        return classification

I was assigning a value (b or w) for a pixel according to its magnitude, to get edges. So, I was following the pattern 1 = True, for is_edge, and 0 = False, for not_edge, and expecting to get an image with white edges and black background. But I noticed that I was getting the opposite, 0 for white and 1 for black. I verified this printing the values. Since I have less edges than background, my number of edges is smaller than my number of background. I for e >> n, and, as can be seen in the image below, my edges are in white color and my background in black.

enter image description here

This is my plot method:

 def generate_data_black_and_white_heat_map(data, x_axis_label, y_axis_label, plot_title, file_path, box_plot=False):
        """
        Generate a heat map of the data
        :param data : the data to be saved
        :param x_axis_label : the x axis label of the data
        :param y_axis_label : the y axis label of the data
        :param plot_title : the title of the data
        :param file_path : the name of the file
        """
        plt.figure()
        plt.title(plot_title)
        plt.imshow(data.data, extent=[0, data.cols, data.rows, 0], cmap='binary')
        plt.xlabel(x_axis_label)
        plt.ylabel(y_axis_label)
        plt.savefig(file_path + '.png')
        plt.close()

I'm wondering if black is 1 and white 0 for matplotlib or if I'm doing something wrong. I guess this is due my cmpa = 'binary'. There is something documentation about how this conversion is done?

Thank you in advance.

Upvotes: 1

Views: 444

Answers (1)

Paul H
Paul H

Reputation: 68116

I'm wondering if black is 1 and white 0 for matplotlib

It sure is.

Try this:

plt.imshow(data.data, extent=[0, data.cols, data.rows, 0], cmap='binary_r')

The _r suffix reverses any colormap.

Upvotes: 1

Related Questions