python opencv阈值红色图像

时间:2016-07-13 05:13:49

标签: python-3.x opencv threshold

我试图在分离红色通道后对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

1 个答案:

答案 0 :(得分: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")