Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Discrete Cosine Transformation of Image with OpenCV

I'm trying to use the OpenCV 2.3 Python wrapper to calculate the DCT for an image. Supposedly, images == numpy arrays == CV matrices, so I thought this should work:

import cv2
img1 = cv2.imread('myimage.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
img2 = cv2.dct(img1)

However, this throws the error:

cv2.error: /usr/local/lib/OpenCV-2.3.1/modules/core/src/dxt.cpp:2247: error: (-215) type == CV_32FC1 || type == CV_64FC1 in function dct

I realize the error means the input should be either a 32-bit or 64-bit single-channel floating point matrix. However, I thought that's how my image should have loaded when specifying grayscale, or at least it should be close enough so that CV2 should be able to figure out the conversion.

What's the appropriate way to convert an image for DCT using cv2?

like image 318
Cerin Avatar asked Oct 28 '11 15:10

Cerin


1 Answers

There doesn't seem to be any easy way to do this with cv2. The closest solution I could find is:

import cv, cv2
import numpy as np

img1 = cv2.imread('myimage.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
h, w = img1.shape[:2]
vis0 = np.zeros((h,w), np.float32)
vis0[:h, :w] = img1
vis1 = cv2.dct(vis0)
img2 = cv.CreateMat(vis1.shape[0], vis1.shape[1], cv.CV_32FC3)
cv.CvtColor(cv.fromarray(vis1), img2, cv.CV_GRAY2BGR)

cv.SaveImage('output.jpg', img2)
like image 155
Cerin Avatar answered Sep 30 '22 02:09

Cerin