How to apply fuzzy c-means segmentation for 2D images?

1.9k views Asked by At

I am working on 2D medical images for segmentation purpose, where I implement fuzzy c-means. I get the error "ValueError: sequence too large; cannot be greater than 32". I need to show a segmentation of whole image through fuzzy c-means. Here is the code, the pic variable dimension is 512x512x3:

from skimage.color import rgb2gray
import numpy as np
from math import log10, sqrt
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import skfuzzy as fuzz


pic = cv2.imread('E:/volumes/Images/corona_4.png')
pic = cv2.cvtColor(pic, cv2.COLOR_BGR2RGB)
cv2.imshow("CT Scan", pic)
cv2.waitKey(0)
cv2.destroyAllWindows()

pic_n = pic.reshape(pic.shape[0]*pic.shape[1], pic.shape[2])
pic_n.shape

def change_color_fuzzycmeans(cluster_membership, clusters):
    img = []
    for pix in cluster_membership.T:
        img.append(clusters[np.argmax(pix)])
    return img

cntr, u, u0, d, jm, p, fpc =fuzz.cluster.cmeans(pic_n,2,2,0.005,100)

new_img = change_color_fuzzycmeans(u,cntr)
fuzzy_img = np.reshape(new_img,pic_n).astype(np.uint8)

The error:

Traceback (most recent call last):

  File "<ipython-input-16-e78a9da752f4>", line 2, in <module>
    fuzzy_img = np.reshape(new_img,pic_n).astype(np.uint8)

  File "C:\Users\User\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py", line 292, in reshape
    return _wrapfunc(a, 'reshape', newshape, order=order)

  File "C:\Users\User\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py", line 66, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)

  File "C:\Users\User\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py", line 46, in _wrapit
    result = getattr(asarray(obj), method)(*args, **kwds)

ValueError: sequence too large; cannot be greater than 32"
1

There are 1 answers

4
Cris Luengo On

You are attempting to reshape one image to the shape of another:

np.reshape(new_img,pic_n)

The second argument should be a shape, not an image. It should read:

np.reshape(new_img,pic_n.shape)

I don't have the ability to test this code right now, but I guess it should read something like this:

data = pic.reshape(pic.shape[0]*pic.shape[1], pic.shape[2]).transpose()
cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(data, 2, 2, 0.005, 100)
output = u.transpose().reshape(pic.shape)