Carlos Diego
Carlos Diego

Reputation: 358

How to plot graphics with the colors of each pixel in the image?

I'm working on image color recognition, so I'm converting the RGB image to Lab because it's the closest color space to human vision. After that, I get each one of the Lab's 3 channels and I want to plot in the 3D graphic the color variations that I identified in the converted image. How do I plot the graphic with the colors of the image?

import cv2
import numpy as np
import urllib
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.pyplot as plt

# Load an image that contains all possible colors.
request = urllib.urlopen('IMD021.png')
image_array = np.asarray(bytearray(request.read()), dtype=np.uint8)
image = cv2.imdecode(image_array, cv2.CV_LOAD_IMAGE_COLOR)

lab_image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
l_channel,a_channel,b_channel = cv2.split(lab_image)

fig = plt.figure()
ax = p3.Axes3D(fig)
ax.scatter(l_channel, a_channel, b_channel, marker='o',  facecolors=cv2.cvtColor(image, cv2.COLOR_BGR2RGB).reshape(-1,3)/255.)

ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
fig.add_axes(ax)
#plt.savefig('plot-15.png')
plt.show()

Exit: enter image description here

Upvotes: 5

Views: 2917

Answers (1)

Ulrich Stern
Ulrich Stern

Reputation: 11301

Here how to get the answer Alexander suggested to work in your case:

# only change to question's code is the ax.scatter() line:
ax.scatter(l_channel, a_channel, b_channel, marker='o',
  facecolors=cv2.cvtColor(image, cv2.COLOR_BGR2RGB).reshape(-1,3)/255.)

Note: The facecolors argument requires RGB, not OpenCV's BGR, and is picky about the shape and type of the color data, hence the reshape and division.

Here the result when the code is applied to this image:enter image description here

Upvotes: 4

Related Questions