Python: 如何从图像中裁剪出特定颜色的区域 (OpenCV, Numpy)

Python: How to cut out an area with specific color from image (OpenCV, Numpy)

所以我一直在尝试编写一个 Python 脚本,该脚本将图像作为输入,然后裁剪出具有特定背景颜色的矩形。然而,对我的编码技巧造成问题的是矩形不是在每个图像中的固定位置(位置将是随机的)。

我不太了解如何管理 numpy 函数。我还阅读了一些有关 OpenCV 的内容,但我对它完全陌生。到目前为止,我只是通过“.crop”功能裁剪了图像,但之后我将不得不使用固定值。

这就是输入图像的外观,现在我想检测黄色矩形的位置,然后将图像裁剪到它的大小。

感谢帮助,提前致谢。

编辑:@MarkSetchell 的方法效果很好,但发现了不同测试图片的问题。另一张图的问题是图片上下各有2个颜色相同的小像素点,导致错误或裁剪不好。

在opencv中你可以使用inRange。这基本上使您指定范围内的任何颜色变为白色,其余颜色变为黑色。这样所有的黄色都会变成白色。

这是文档:https://docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html

更新答案

我已经更新了我的答案以应对与黄色框相同颜色的嘈杂离群像素斑点。这是通过 运行 一个 3x3 中值滤波器首先在图像上去除斑点来实现的:

#!/usr/bin/env python3

import numpy as np
from PIL import Image, ImageFilter

# Open image and make into Numpy array
im = Image.open('image.png').convert('RGB')
na = np.array(im)
orig = na.copy()    # Save original

# Median filter to remove outliers
im = im.filter(ImageFilter.MedianFilter(3))

# Find X,Y coordinates of all yellow pixels
yellowY, yellowX = np.where(np.all(na==[247,213,83],axis=2))

top, bottom = yellowY[0], yellowY[-1]
left, right = yellowX[0], yellowX[-1]
print(top,bottom,left,right)

# Extract Region of Interest from unblurred original
ROI = orig[top:bottom, left:right]

Image.fromarray(ROI).save('result.png')

原答案

好的,你的黄色是rgb(247,213,83),所以我们要求出所有黄色像素点的X,Y坐标:

#!/usr/bin/env python3

from PIL import Image
import numpy as np

# Open image and make into Numpy array
im = Image.open('image.png').convert('RGB')
na = np.array(im)

# Find X,Y coordinates of all yellow pixels
yellowY, yellowX = np.where(np.all(na==[247,213,83],axis=2))

# Find first and last row containing yellow pixels
top, bottom = yellowY[0], yellowY[-1]
# Find first and last column containing yellow pixels
left, right = yellowX[0], yellowX[-1]

# Extract Region of Interest
ROI=na[top:bottom, left:right]

Image.fromarray(ROI).save('result.png')


您可以在终端中使用 ImageMagick:

做完全相同的事情
# Get trim box of yellow pixels
trim=$(magick image.png -fill black +opaque "rgb(247,213,83)" -format %@ info:)

# Check how it looks
echo $trim
251x109+101+220

# Crop image to trim box and save as "ROI.png"
magick image.png -crop "$trim" ROI.png

如果仍在使用 ImageMagick v6 而不是 v7,请将 magick 替换为 convert

我看到的是侧面和顶部的深灰色和浅灰色区域,一个白色区域,以及一个黄色矩形,白色区域内有灰色三角形。

我建议的第一阶段是将图像从 RGB 颜色 space 转换为 HSV 颜色 space。
HSV space中的S颜色通道是"color saturation channel".
所有无色 (gray/black/white) 都是零,黄色像素在 S 通道中高于零。

下一阶段:

  • 在 S 通道上应用阈值(将其转换为二值图像)。
    黄色像素变为 255,其他变为零。
  • 在 thresh 中查找轮廓(仅查找外部轮廓 - 仅查找矩形)。
  • 反转矩形内像素的极性。
    灰色三角形变为 255,其他像素为零。
  • 在 thresh 中查找轮廓 - 查找灰色三角形。

代码如下:

import numpy as np
import cv2

# Read input image
img = cv2.imread('img.png')

# Convert from BGR to HSV color space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Get the saturation plane - all black/white/gray pixels are zero, and colored pixels are above zero.
s = hsv[:, :, 1]

# Apply threshold on s - use automatic threshold algorithm (use THRESH_OTSU).
ret, thresh = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# Find contours in thresh (find only the outer contour - only the rectangle).
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]  # [-2] indexing takes return value before last (due to OpenCV compatibility issues).

# Mark rectangle with green line
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

# Assume there is only one contour, get the bounding rectangle of the contour.
x, y, w, h = cv2.boundingRect(contours[0])

# Invert polarity of the pixels inside the rectangle (on thresh image).
thresh[y:y+h, x:x+w] = 255 - thresh[y:y+h, x:x+w]

# Find contours in thresh (find the triangles).
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]  # [-2] indexing takes return value before last (due to OpenCV compatibility issues).

# Iterate triangle contours
for c in contours:
    if cv2.contourArea(c) > 4:  #  Ignore very small contours
        # Mark triangle with blue line
        cv2.drawContours(img, [c], -1, (255, 0, 0), 2)

# Show result (for testing).
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

HSV 颜色的 S 颜色通道 space:

thresh - 阈值后 S:

thresh 反转矩形极性后:

结果(标出矩形和三角形):


更新:

如果背景上有一些彩色点,您可以裁剪最大的彩色轮廓:

import cv2
import imutils  # https://pypi.org/project/imutils/

# Read input image
img = cv2.imread('img2.png')

# Convert from BGR to HSV color space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Get the saturation plane - all black/white/gray pixels are zero, and colored pixels are above zero.
s = hsv[:, :, 1]

cv2.imwrite('s.png', s)

# Apply threshold on s - use automatic threshold algorithm (use THRESH_OTSU).
ret, thresh = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# Find contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = imutils.grab_contours(cnts) 

# Find the contour with the maximum area.
c = max(cnts, key=cv2.contourArea)

# Get bounding rectangle
x, y, w, h = cv2.boundingRect(c)

# Crop the bounding rectangle out of img
out = img[y:y+h, x:x+w, :].copy()

结果: