如何在python中使用opencv处理图像? [英] how to process image with opencv in python?

查看:194
本文介绍了如何在python中使用opencv处理图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用opencv库中的边缘检测算法。
这是一段python代码:

I want to use edge detection algorithms from opencv library. Here is a piece of python code:

from opencv.cv import *
from opencv.highgui import *

img = cvLoadImage ('xxx.jpg')
cvNamedWindow ('img')
cvShowImage ('img', img)
cvWaitKey ()

canny = cvCreateImage (cvSize (img.width, img.height), 8, 3)
cvCanny (img, canny, 50, 200)

harris = cvCreateImage (cvSize (img.width, img.height), 8, 3)
cvCornerHarris (img, harris, 5, 5, 0.1)

加载和显示图像工作正常,但canny和harris转换失败。

cvCanny 失败:

Loading and showing image works fine, but canny and harris transformations fail.
cvCanny fails with:

RuntimeError:  openCV Error:
    Status=Unsupported format or combination of formats
    function name=cvCanny
    error message=
    file_name=cv/cvcanny.cpp
    line=72

cvCornerHarris 因此错误而失败:

RuntimeError:  openCV Error:
    Status=Assertion failed
    function name=cvCornerHarris
    error message=src.size() == dst.size() && dst.type() == CV_32FC1
    file_name=cv/cvcorner.cpp
    line=370

从这条消息我可以推断出加载的图像格式无效。但我不明白如何转换它。

以下是一些 img 字段的值:

From this messages I can infer that loaded image has invalid format. But I don't understand how to convert it.
Here are values of some img fields:

img.type = 1111638032
img.nChannels = 3
img.depth = 8


推荐答案

这是固定代码。请参阅内联评论。长话短说:你的数据类型错了。阅读 API

Here's fixed code. See comments inline. Long story short: your data types were wrong. Read the API.

try:
    from opencv.cv import *
    from opencv.highgui import *
except:
    #
    # Different OpenCV installs name their packages differently.
    #
    from cv import *

if __name__ == '__main__':
    import sys
    #
    # 1 = Force the image to be loaded as RGB
    #
    img = LoadImage (sys.argv[1], 1)
    NamedWindow ('img')
    ShowImage ('img', img)
    WaitKey ()

    #
    # Canny and Harris expect grayscale  (8-bit) input.
    # Convert the image to grayscale.  This is a two-step process:
    #   1.  Convert to 3-channel YCbCr image
    #   2.  Throw away the chroma (Cb, Cr) and keep the luma (Y)
    #
    yuv = CreateImage(GetSize(img), 8, 3)
    gray = CreateImage(GetSize(img), 8, 1)
    CvtColor(img, yuv, CV_BGR2YCrCb)
    Split(yuv, gray, None, None, None)

    canny = CreateImage(GetSize(img), 8, 1)
    Canny(gray, canny, 50, 200)
    NamedWindow ('canny')
    ShowImage ('canny', canny)
    WaitKey()

    #
    # The Harris output must be 32-bit float.
    #
    harris = CreateImage (GetSize(img), IPL_DEPTH_32F, 1)
    CornerHarris(gray, harris, 5, 5, 0.1)

这篇关于如何在python中使用opencv处理图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆