如何在Python中使用OpenCV处理图像?

5 投票
3 回答
12602 浏览
提问于 2025-04-16 11:51

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

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出错了,错误信息是:

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字段的值:

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

3 个回答

2

你可以一步就把一张图片转换成灰度图,而不是分两步来做:

gray = cv.CreateMat(img.height, img.width, cv.CV_8UC1)
cv.CvtColor(img, gray, cv.CV_BGR2GRAY)
8

对于其他对类似问题感兴趣的人,我推荐你去看看 http://simplecv.org

这里有一段我写的代码,它可以对从网络摄像头获取的图像进行线条检测。它甚至可以通过http显示图像。胡须检测

import SimpleCV
import time

c = SimpleCV.Camera(1)
js = SimpleCV.JpegStreamer() 

while(1):
  img = c.getImage()
  img = img.smooth()
  lines = img.findLines(threshold=25,minlinelength=20,maxlinegap=20)
  [line.draw(color=(255,0,0)) for line in lines]
  #find the avg length of the lines
  sum = 0
  for line in lines:
      sum = line.length() + sum
  if sum:
      print sum / len(lines)
  else:
      print "No lines found!"
  img.save(js.framebuffer)
  time.sleep(0.1)

你可以查看我为这个项目制作的内容,网址是 http://labs.radiantmachines.com/beard/,它可以检测你的脖子胡须有多长哦 :)

6

这是修正后的代码。请查看代码中的注释。简单来说,你的数据类型设置错了。建议你阅读一下这个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)

撰写回答