Tuesday, December 31, 2013

Qt Tips

Recently I have been developing with Qt. I don't want to waste the value of my time spent on searching for solutions to those problems, so recording all my quesitons will be much consoling.

1. QWebView loads html from resource
As you can search on the Net, many peole write codes like
webView->setUrl(QUrl::fromLocalFile(":/html/homepage.html"));
But it won't work. Using qDebug() to output its url, the only thing you can get is "about:blank". You should write like this:
webView->setUrl(QUrl("qrc:///html/homepage.html"));

P.S. To get your resource path, just open the resource editor in Qt creator, right-click on the target resource and choose "Copy Resource Path to clipboard".


to be continued...

Monday, December 30, 2013

How did I solve frequent crashing of libjpeg?

Recently I was using libjpeg to support my program but as most people met, it crashed frequently. At first time it crashed at jpeg_read_header() and I unexpectedly linked to another library solving this crash but met it again at jpeg_finish_decompress(). Although googling it hardly online, I got little help. Today, I used libjpeg-turbo (jpeg-static.lib) and suddenly found it working! What an exciting moment!

Platform: Windows XP professional
Compiler: Visual Studio 2010 C++
File: rw_dct.c, setup.py, rw_dct_test.py (I need to compile and get PYD file)

# setup.py
#!/usr/bin/env python2
import os
from distutils.core import setup, Extension
from distutils.sysconfig import get_python_lib

numpy_import = os.path.join(get_python_lib(), 'numpy', 'core', 'include')

mod_rw_dct = Extension('rw_dct',
                       sources=['rw_dct.c'],
                       libraries=['jpeg-static'],
                       include_dirs=[numpy_import])

setup(name='Get Pyd',
      version='0.1',
      description='Compiling Pyd file test',
      license='GNU GPLv3',
      ext_modules=[mod_rw_dct])

Thursday, December 12, 2013

How to install StegoTool

I have spent five days on the installation work of StegoTool. To deal with problems, it was common for me to question on StackOverflow, although I seldom asked due to the thought that someone must already meet my problems. But this experience taught me that reading official documents is very important. Recording my installation will be much meaningful for me, during which I always got stuck.

Official Site of this StegoTool is here.

Python : python-2.7.5.msi
SciPy & NumPy : scipy-0.13.2-win32-superpack-python2.7.exe, numpy-1.8.0-win32-superpack-python2.7.exe
PIL : PIL-1.1.7.win32-py2.7.exe
Matplotlib : matplotlib-1.3.1.win32-py2.7.exe
PyQt : PyQt4-4.10.3-gpl-Py2.7-Qt4.8.5-x32.exe
Qt : qt-windows-opensource-5.1.1-mingw48_opengl-x86-offline.exe

Libjpeg : jpegsr8b.zip (after "./configure", generate exe from ckconfig.c to generate jconfig.h and then "make")
MSYS & MinGW : MSYS-1.0.11.exe, MinGw4.5.0

SIP : sip-4.15.3.zip (Don't use MSYS, all could be done in cmd. "python configure.py -p win32-g++", set "mingw/bin" in your environment variable and then "mingw32-make", "mingw32-make install")
SetupTools : setuptools-2.0.tar.gz
Dateutil : python-dateutil-2.2.tar.gz
Pyparsing : pyparsing-2.0.1.tar.gz

All above is what you will need to install the tool. Most of my time was spent on fixing endless problems after installing Enthought Canopy (academic version). I thought it would be convenient but the fact was the opposite. So this morning installing libraries seperately made it through. Here is how the tool goes:


If you are to run on windows like me, please be sure to do the following changes:
1. StegoTool.py
def load_crypto_schemes():
    schemedict = {}
    cryptodir = os.path.join(WORK_DIR, config.CRYPTOFOLDER)
    for scheme in os.listdir(cryptodir):
        if scheme != '__init__.py' and scheme.endswith('.py'):
            name = scheme[:-3]
            # please be sure that CRYPTOFOLDER is written in UNIX form
            mod_name = (config.CRYPTOFOLDER + name).replace('/', '.')
            try:
                mod = __import__(mod_name, fromlist=mod_name)
                schemedict[name] = getattr(mod, name)
            except ImportError:
                logger.warning('"%s is not a Python module!' % name)
            except AttributeError:
                logger.warning('"%s does not contain a corresponding class'
                               % name)
    return schemedict

2. qtwidgets.py
class ImageWidget(QtGui.QWidget):
    """ Widget to display an image """

    def __init__(self, title, img, parent=None):
        """ img should be an PIL image. """
        QtGui.QWidget.__init__(self, parent)
        self.ui = parent.ui
        layout = QtGui.QVBoxLayout()
        label = QtGui.QLabel()
        # directly wrting "image=ImageQt.ImageQt(img)" works fine on linux but crash on windows
        # we can find solution here - http://skilldrick.co.uk/2010/03/pyqt-pil-and-windows/
        if os.name == 'nt':
            QtImage = ImageQt.ImageQt(img)
            image = QtImage.copy()
        else:
            image = ImageQt.ImageQt(img)

        pixmap = QtGui.QPixmap.fromImage(image)
        label.setPixmap(pixmap)
        layout.addWidget(label)

        save_image = QtGui.QPushButton('Save Image')

        def save():
            if hasattr(img, 'tmp_file'):
                shutil.copy(img.tmp_file, path)
            else:
                try:
                    img.save(str(path))
                except Exception:
                    self.ui.display_error('Could not save image!')
            

        save_image.clicked.connect(save)
        layout.addWidget(save_image)
        self.setLayout(layout)
        self.setWindowTitle(title)

3. Problems about using libjpeg please refer to  "How did I solve frequent crashing of libjpeg?"



Saturday, December 7, 2013

LSB in steganography

Steganography is very interesting. A simple method is LSB. We hide our information bit by bit in every pixel, and the number of bits and position of hidden bits are determined by our program. I've finished LSB for a long time but don't spread my implementation considering my poor programming ability. But impressed by my "elegant" code, I decided to share it in this blog. (In fact, I was inspired by someone else's code but couldn't think of where and who, please contact me if you have any opinions)

MATLAB makes people process image quite easily, so I used MATLAB to finish it. Here is my code :

% secret : matrix made of hidden infomation
% carrier: matrix made of pixel
% extract: matrix to store hidden information
% N: position, usually equaling 1
carrier = bitor( bitand(carrier, bitcmp(2^N-1, 8)), secret );
extract = uint8( bitand( 255, bitshift(carrier, 8-N)));

P.S. To implement a function, you might need dec2bin() mat2str() bin2dec() for support.