2

Python 3.3でTkinterとpython.boostを使用しています。

中央に画像を表示するシンプルな GUI を作成したいと考えています。イメージは、double 値を使用して C++ クラスに格納されます。tkinter を使用して画像を表示するには、 PhotoImageオブジェクトを作成する必要があります。

Image.fromstring(mode、size、data、decoder、parameters)メソッドを使用して PhotoImage オブジェクトを作成できることを読みました。私が考えているのは、バッファを std::string に変換する関数を作成すると、PhotoImage オブジェクトを作成できるということです。

私のC++クラスは次のとおりです。

class DoubleImage
{
    double* m_dBuffer; // Values from 0 to 1

public:
    DoubleImage(const char* fileName, const int width, const int height);

    /* Class Functions  */

    std::string toString( void ) {
        double *pSrc  = m_dBuffer;
        int size = getWidth() * getHeight() * getChannels();

        char* buffer = new char[size];
        char* pbuffer = buffer;

        for ( int i = 0; i < size; ++i, ++pSrc, ++pbuffer ) {
            *pbuffer = ((char) (*pSrc * 255.0));
        }

        std::string ret(buffer);

        delete[] buffer;

        return ret;
    }
};

Pythonブーストコードは次のとおりです。

using namespace boost::python;

BOOST_PYTHON_MODULE(ImageModule)
{

    class_<DoubleImage>("DoubleImage", init<const char*, const int, const int>()) 
        .add_property("width", &DoubleImage::getWidth)
        .add_property("height", &DoubleImage::getHeight)
        .add_property("channels", &DoubleImage::getChannels)
        // Some functions ...
        .def("toString", &DoubleImage::toString)
    ; 
}

しかし、Python で toString を実行すると、次のエラーが発生します。

>>> from ImageModule import *
>>> img = DoubleImage('001.png', 300, 200)
>>> buffer = img.toString()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x86 in position 155: invalid start byte
>>>

2 つの質問があります。まず、何が足りないのでしょうか?? 次に、このエラーを解決したら、PhotoImage オブジェクトを作成するためにどのパラメーターを使用する必要がありますか?

4

1 に答える 1

0

最後に、多くの苦しみの後に解決策を見つけました:P

まず、関数toStringを次のように変更する必要があります。

std::string DoubleImage::toString( void ) {
    ECV_CHECK_ERROR ( m_eType == IT_UKNOWN, "The image is not initialized!" );

    double *pSrc  = (double *) m_cvImage.data;
    long size = getWidth() * getHeight() * getChannels();

    std::string ret(size, ' ');

    for ( long i = 0; i < size; ++i, ++pSrc ) {
         ret[i] = ((char) (*pSrc * 255.0));
    }

    return ret;
}

それ以外の場合、結果の std::string は全長になりません (コンストラクターが最初の '\0' を検索するため)。さらに、奇妙なエラー " UnicodeDecodeError " は、python 3.3 を使用した場合にのみ発生します。Python 2.7 を使用することで、問題は解決されます。そのため、画像処理には python 2.7 を使用することをお勧めします。

次に、 PIL モジュールをインストールしました(これも python 2.7 でのみ利用可能です)。次に、Python で次のコードを使用して PhotoImage オブジェクトを作成します。

>>> from ImageModule import *
>>> from PIL import image
>>> from ImageTk import PhotoImage
>>> img = DoubleImage('001.png', 300, 200)
>>> buffer = img.toString()
>>> img_pil = Image.fromstring('RGB', [300, 200], buffer, 'raw', 'BGR', 300 * 3, 0)
>>> tk_image = PhotoImage(img_pil)

ここで、300 は画像、200 は画像の高さ、RGB は出力形式、BGR は入力形式 (IplImage)、3 はチャンネル (3 * 300 画像ステップ) です。その後、すべてが魅力のように機能します:)

于 2012-12-03T13:49:08.160 に答える