0

I receive an image as binary in web.data() and decode it with cv2.imdecode. The result is an image. I can succefully run some blob detection on it no problem. Getting width and height however turned out to be a problem. Here's the code I'm using (found here and here) with the error messages I get. Neither of the two suggested ways of doing this works, why is that?

imageDecoded = cv2.imdecode(np.frombuffer(web.data(), dtype='uint8'), cv2.CV_LOAD_IMAGE_GRAYSCALE)

# https://stackoverflow.com/questions/13033278/image-size-python-opencv
height, width = cv.GetSize(imageDecoded)        # <class 'cv2.error'> Array should be CvMat or IplImage

# https://stackoverflow.com/questions/32971241/how-to-get-image-width-and-height-in-opencv
height, width, channels = imageDecoded.shape    # <type 'exceptions.AttributeError'> 'NoneType' object has no attribute 'shape'
Community
  • 1
  • 1
null
  • 5,207
  • 1
  • 19
  • 35
  • if the `retval` of the function is a `numpy.array` you can do `height, width = imageDecoded.shape` – Francesco Nazzaro Sep 13 '16 at 12:51
  • @FrancescoNazzaro how is telling me "*If you had something that worked, you could do this...*" helpful? I tried `shape`, which didn't work. It is aparently not a `numpy.array`, but a `NoneType`. `np.frombuffer` returns a 1D array which is not helpful. – null Sep 13 '16 at 13:01
  • 1
    Not a Python expert, but make sure that the buffer contains valid data and the `imageDecoded` is valid. From the doc: _If the buffer is too short or contains invalid data, the empty matrix/image is returned._ That could explain why you get `NoneType` – Miki Sep 13 '16 at 17:44
  • @Miki it's the strangest thing: the return value from `np.frombuffer` is a large 1D array, yet the subsequent blob detection I perform on `imageDecoded` works flawlessly. I don't think you can perform said detection without knowledge of the size because that determines what pixels are neighbours, yet at the intermediate step that is `np.frombuffer` the size information seems to be missing already. – null Sep 13 '16 at 18:06
  • 1
    Well, `np.frombuffer` must return a large 1D array, which is your image encoded/compressed somehow, tipically jpg or png. `cv2.imdecode` accepts the _compressed_ bytes, and uncompresses/decodes them to a numpy array of correct shape. This is why you should be able to get rows and columns as `(h, w) = image.shape[:2]`. If your image has only 1 channel (you used `LOAD_IMAGE_GRAYSCALE`) `shape` will return only 2 values (omitting the channels). If blob detection is working ok, then probably the image is decoded correctly, and you just need to remove the `channels` return value (just a guess). – Miki Sep 13 '16 at 18:21

0 Answers0