'img = the image
patchsize = the patch size (ususally 11x11)
count = total codes
patch_arrangement = how are the patches grided in the image (eg 128 = (8x16) 256=(16x16) )
spacersz = the number of pixels between patches'

def _img2Codebook(self, img, patchsize, count, patch_arrangement, spacersz):

    img = img.toHLS()
    lmat = cv.CreateImage((img.width, img.height), cv.IPL_DEPTH_8U, 1)
    patch = cv.CreateImage(patchsize, cv.IPL_DEPTH_8U, 1)
    cv.Split(img.getBitmap(), None, lmat, None, None)
    w = patchsize[0]
    h = patchsize[1]
    length = (w * h)
    retVal = np.zeros(length)
    for widx in range(patch_arrangement[0]):
        for hidx in range(patch_arrangement[1]):
            x = ((widx * patchsize[0]) + ((widx + 1) * spacersz))
            y = ((hidx * patchsize[1]) + ((hidx + 1) * spacersz))
            cv.SetImageROI(lmat, (x, y, w, h))
            cv.Copy(lmat, patch)
            cv.ResetImageROI(lmat)
            retVal = np.vstack((retVal, np.array(patch[:, :]).reshape(length)))
    retVal = retVal[1:, :]
    return retVal
