使用Opencv Python查找灰度或彩色图像

3
我希望能够使用openCV Python自动化和过滤灰度和彩色图像。我已经尝试在彩色和灰度图像上运行直方图,以下是结果。

GrayScale Vs Color Image

尝试的代码:

import cv2
import numpy as np
import sys
img = cv2.imread(sys.argv[1])
h = np.zeros((300,256,3))

bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for ch, col in enumerate(color):
    hist_item = cv2.calcHist([img],[ch],None,[256],[0,256])
    cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
    hist=np.int32(np.around(hist_item))
    pts = np.column_stack((bins,hist))
    cv2.polylines(h,[pts],False,col)
h=np.flipud(h)
cv2.imshow('colorhist',h)
cv2.waitKey(0)

我可以不为每个文件创建直方图图表而自动化相同的过程吗?
3个回答

2

在上面的通道比较基础上,使用numpy数组切片并假设图像是RGB或HSV颜色空间:

def isbw(img):
    #img is a numpy.ndarray, loaded using cv2.imread
    if len(img.shape) > 2:
        looks_like_rgbbw = not False in ((img[:,:,0:1] == img[:,:,1:2]) == (img[:,:,1:2] ==  img[:,:,2:3]))
        looks_like_hsvbw = not (True in (img[:,:,0:1] > 0) or True in (img[:,:,1:2] > 0))
        return looks_like_rgbbw or looks_like_hsvbw
    else:
        return True

易于扩展以检查其他颜色空间条件。

未经广泛测试的“边缘/异常”情况(例如其他可能的格式)。对于仅具有红色通道的(BGR)图像将失败,因为这将看起来像黑白HSV图像,因此根据图像主题信任于cv2 cvtColor转换为BGR格式可能更好。其他“边缘”情况可能存在。


1

这里有一段 C++ 代码示例,用于确定图像是彩色还是灰度。我认为你可以很容易地将其转换为 Python。

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "iostream"

using namespace cv;

bool isGrayImage( Mat img ) // returns true if the given 3 channel image is B = G = R
{
    Mat dst;
    Mat bgr[3];
    split( img, bgr );
    absdiff( bgr[0], bgr[1], dst );

    if(countNonZero( dst ))
        return false;

    absdiff( bgr[0], bgr[2], dst );
    return !countNonZero( dst );
}

int main(int argc, char** argv)
{
    static const char* str[] = {" is a COLOR image"," is a GRAY image"};
    char* filename = argc >= 2 ? argv[1] : (char*)"fruits.jpg";
    Mat src = imread(filename);

    if(src.data)
    {
        std::cout << filename << str[isGrayImage( src )] << std::endl;
        imshow(filename, src );
        waitKey();
    }
    return 0;
}

0
你可以使用CV_LOAD_IMAGE_COLOR (1)标记 (imread 文档) 将图像作为彩色加载:
img = cv2.imread(sys.argv[1], 1)

然后检查每个像素的红、绿、蓝通道是否具有相同的像素值。

for x in range(0, width):
  for y in range(0, height):
    if img[x, y, 0] == img[x, y, 1] == img[x, y, 2]:
      # needs to be true for all pixels
    else:
      # not grayscale

当使用CV_LOAD_IMAGE_ANYDEPTH标志加载图像时,您还可以尝试使用channels方法。


宽度和高度的值是多少? - jOSe
图像的宽度和高度。 - Aleksander Grzyb
我已经包括 height,width,channel = img.shape 现在程序可以运行。但是我得到了一个"IndexError"错误。 - jOSe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接