【问题标题】:python opencv threshold red imagepython opencv阈值红色图像
【发布时间】:2016-11-15 12:52:56
【问题描述】:

我试图在分离红色通道后对 BGR 图像进行阈值处理,但是 我的代码总是返回“分段错误”。

import numpy as np
import cv2
def mostrarVentana (titulo, imagen):
  print('Mostrando imagen')
  cv2.imshow(titulo, imagen)
  k = cv2.waitKey(0)
  if k == 27:         # wait for ESC key to exit
     cv2.destroyAllWindows()

img = cv2.imread('RepoImagenes/640x480/P5.jpg', 1)  # loading image in BGR
redImg = img[:, :, 2]  # extracting red channel
rbin, threshImg = cv2.threshold(redImg, 58, 255, cv2.THRESH_BINARY)  # thresholding
mostrarVentana('Binary image', threshImg)

我已阅读有关如何使用 threshold() 函数的文档,但我不知道出了什么问题。我只需要在红色通道上工作,我该如何完成?

我正在使用 python 3.4 和 opencv 3.1.0

【问题讨论】:

  • 猜测最有可能是找不到文件...使用调试器查看失败的行,并检查变量。
  • @Photon 图像文件已正确加载,如果我用阈值函数注释该行,那么代码可以正常工作,因为我没有调用 threshImg 变量。

标签: python-3.x opencv threshold


【解决方案1】:

首先opencv提供了一个简单的API来分割n-channel图像,使用cv2.split()会返回图像中各种通道的列表。

您的mostrarVentana 方法中还有一个错误,您从未创建过cv2.namedWindow(),并且您直接引用了cv2.imshow(),但您不能简单地cv2.imshow(),而不创建cv2.namedWindow()

另外,您必须确保图像已正确加载,然后访问所需的通道,否则会导致奇怪的错误。您的带有一些场景处理的代码如下所示:

import numpy as np
import cv2
def mostrarVentana (titulo, imagen):
    print('Mostrando imagen')
    cv2.namedWindow(titulo, cv2.WINDOW_NORMAL)
    cv2.imshow(titulo,imagen)
    k = cv2.waitKey(0)
    if k == 27:         # wait for ESC key to exit
       cv2.destroyAllWindows()

img = cv2.imread('RepoImagenes/640x480/P5.jpg', 1)  # loading image in BGR
print img.shape #This should not print error response

if not img is None and len(img.shape) == 3 and img.shape[2] == 3:
    blue_img, green_img, red_img = cv2.split(img)  # extracting red channel
    rbin, threshImg = cv2.threshold(red_img, 58, 255, cv2.THRESH_BINARY)  # thresholding
    mostrarVentana('Binary image', threshImg)

else:
    if img is None:
        print ("Sorry the image path was not valid")
    else:
        print ("Sorry the Image was not loaded in BGR; 3-channel format")

【讨论】:

  • 修改变量名时可能会出现一些拼写错误,请查看这段代码。
  • 运行代码ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()时出现下一个错误,所以我将if条件更改为if img.all() and len(img.shape) == 3 and img.shape[2] == 3:之后我检查了.jpg文件的路径,它一直说路径无效.我什至将图像移动到与 python 源代码相同的目录。
  • 很抱歉错过了img.all() 的东西,就图像路径而言,您必须在img = cv2.imread('RepoImagenes/640x480/P5.jpg', 1) 之后放置一个print img.shape,同时始终使用完整的限定路径,例如“C:\下载\this.png”或“/Users/yourName/Downloads/this.png”
  • 我的 opencv 二进制文件是否有可能失败?我已经尝试过img.all()img.any();第一个返回图像路径无效,后者返回Segmentation fault。我还使用了完全限定路径。
  • 我已经编辑了答案以检查图像是否为无,并且在加载图像后也 pring img.shape
猜你喜欢
  • 2019-12-03
  • 2012-08-25
  • 2015-09-11
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多