Python:如何从图像中切出具有特定颜色的区域(OpenCV、Numpy)

Kea*_*anu 7 python opencv numpy crop python-imaging-library

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

我不太明白如何管理 numpy 函数。我也读过一些关于 OpenCV 的东西,但我对它完全陌生。到目前为止,我只是通过“.crop”功能裁剪了图像,但随后我将不得不使用固定值。

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

感谢帮助,提前致谢。

图片外观示例(初始示例)

更新的图像,它的真实外观

编辑:@MarkSetchell 的方式效果很好,但发现不同的测试图片存在问题。另一张图片的问题是图片顶部和底部有2个颜色相同的小像素,导致错误或裁剪不好。

Mar*_*ell 6

更新答案

我已经更新了我的答案,以处理与黄色框颜色相同的噪声异常像素斑点。这是通过首先在图像上运行 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')
Run Code Online (Sandbox Code Playgroud)

原答案

好的,你的黄色是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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


您可以在终端中使用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
Run Code Online (Sandbox Code Playgroud)

如果仍在使用ImageMagick v6 而不是 v7,请替换magickconvert.

  • @Karlo,你永远不应该期望 Stack Overflow 中的答案能够涵盖你没有发布的案例。问题应该是具体的而不是笼统的。您可以尝试再发布一些图像,但请务必展示您为解决问题所做的努力(发布您的代码)。 (2认同)

Rot*_*tem 5

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

我建议的第一阶段是将图像从 RGB 颜色空间转换为HSV颜色空间。
HSV 空间中的S颜色通道,是“颜色饱和通道”。
S 通道中所有无色(灰/黑/白)均为零,黄色像素高于零。

接下来的阶段:

  • 在 S 通道上应用阈值(将其转换为二值图像)。
    黄色像素变为 255,其他像素变为 0。
  • 在 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()
Run Code Online (Sandbox Code Playgroud)

HSV 颜色空间中的 S 颜色通道:
在此输入图像描述

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()
Run Code Online (Sandbox Code Playgroud)

结果:
在此输入图像描述

  • 您可以裁剪最大的彩色轮廓。我更新了我的帖子 (2认同)