I’m having trouble segmenting an image

Asked

Viewed 36 times

0

I’m creating a mix of image segmentation by k-Means and Spectral clustering, but I have a big problem at the end. I’ll leave the code here:

import cv2
import timeit
import time
import numpy as np
from scipy.ndimage.filters import gaussian_filter
import matplotlib.pyplot as plt
import skimage
from skimage.transform import rescale
from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering
from sklearn.utils.fixes import parse_version

start = timeit.timeit()
imag = cv2.imread("13-08-20-9.bmp")
pixel_values = imag.reshape((-1, 3))
pixel_values = np.float32(pixel_values)
#print(pixel_values.shape)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 500, 0.2)
k = 2
_, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
centers = np.uint8(centers)
labels = labels.flatten()
segmented_imag = centers[labels.flatten()]
segmented_imag = segmented_imag.reshape(imag.shape)
masked_imag = np.copy(imag)
masked_imag = masked_imag.reshape((-1, 3))
cluster = 0
masked_imag[labels == cluster] = [0, 0, 0]
masked_imag = masked_imag.reshape(imag.shape)
print("Segmentando com K-Means Clustering...")
print("Tempo de Processamento: ", start)
if parse_version(skimage.__version__) >= parse_version('0.14'):
    rescale_params = {'anti_aliasing': False, 'multichannel': False}
else:
    rescale_params = {}
orig_coins = masked_imag
smoothened_coins = gaussian_filter(orig_coins, sigma=2)
rescaled_coins = rescale(smoothened_coins, 0.2, mode="reflect",
                         **rescale_params)
graph = image.img_to_graph(rescaled_coins)
beta = 10
eps = 1e-6
graph.data = np.exp(-beta * graph.data / graph.data.std()) + eps
N_REGIONS = 40
for assign_labels in ('kmeans', 'discretize'):
    t0 = time.time()
    labels = spectral_clustering(graph, n_clusters=N_REGIONS,
                                 assign_labels=assign_labels, random_state=42)
    t1 = time.time()
    labels = labels.reshape(rescaled_coins.shape)

    plt.figure(figsize=(5, 5))
    plt.imshow(rescaled_coins, cmap=plt.cm.gray)
    for l in range(N_REGIONS):
        plt.contour(labels == l,
                    colors=[plt.cm.nipy_spectral(l / float(N_REGIONS))])
    plt.xticks(())
    plt.yticks(())
    title = 'Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0))
    print(title)
    plt.title(title)
plt.show()

In part:

for l in range(N_REGIONS):
            plt.contour(labels == l,
                        colors=[plt.cm.nipy_spectral(l / float(N_REGIONS))])

This error appears:

Traceback (most recent call last):
  File "C:\Users\gabri\PycharmProjects\pythonProject2\Teste.py", line 56, in <module>
    colors=[plt.cm.nipy_spectral(l / float(N_REGIONS))])
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\pyplot.py", line 2553, in contour
    **kwargs)
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\__init__.py", line 1438, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\axes\_axes.py", line 6324, in contour
    contours = mcontour.QuadContourSet(self, *args, **kwargs)
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\contour.py", line 816, in __init__
    kwargs = self._process_args(*args, **kwargs)
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\contour.py", line 1430, in _process_args
    x, y, z = self._contour_args(args, kwargs)
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\contour.py", line 1485, in _contour_args
    x, y = self._initialize_x_y(z)
  File "C:\Users\gabri\PycharmProjects\pythonProject2\venv\lib\site-packages\matplotlib\contour.py", line 1564, in _initialize_x_y
    raise TypeError(f"Input z must be 2D, not {z.ndim}D")
TypeError: Input z must be 2D, not 3D

Please, if any good soul in this world can help me, I will be eternally grateful!

  • As the error points out, z should be a 2D or 3d array. Try these two lines: z = np.array(z) and z = z.reshape((len(x), len(y)))

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.