Python:获取裁剪区域外的平均颜色

Python: get average colour outside cropped area

我有一张图像,其中有一个对象是我使用 Canny 滤镜从图像中裁剪掉的

import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image

# load image
img = cv2.imread('dataset/example.png')

#.
#.
#.
#.
#.

# canny edge detection then find the non-zero min-max coords of canny 

#.
#.
#.
#.
#.

# ROI
roi = img[y1:y2, x1:x2]
## crop ROI
cropped = np.array(img)
cropped[y1:y2, x1:x2] = (0, 0, 0)
bg = Image.fromarray(cropped)

这是我得到的结果:

有没有办法select裁剪区域以外的区域(黑框)?基本上 select 取 cropped[y1:y2, x1:x2] 的倒数,然后得到该背景的平均颜色?

您可以使用 cv2.mean 和面具:

# create a mask from coordinages
mask = cv2.rectangle(np.zeros(img.shape[:2],'uint8'), (y1,x1), (y2,x2), 255, -1)

# out
means = cv2.mean(img, mask=mask)

您不能裁剪非 4 个顶点的多边形 - 请记住您正在使用 矩阵 。如果要得到非黑色区域的contours,可以先用0的阈值得到一个二进制掩码。这将使高于该值的所有内容呈现为白色。然后获取该二进制掩码的轮廓,如下所示:

# importing cv2 & numpy
import numpy as np
import cv2

# image path
path = "C://opencvImages//"
fileName = "squareTest.png"

# Reading an image in default mode:
inputImage = cv2.imread(path + fileName)

# Grayscale conversion:
grayscaleImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Fixed Thresholding:
thresholdValue = 0
_, binaryImage = cv2.threshold(grayscaleImage, thresholdValue, 255, cv2.THRESH_BINARY)

这是您获得的面具:

现在,简单的得到轮廓:

# Find the contours on the mask image:
contours, hierarchy = cv2.findContours(binaryImage, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

# Draw the contours on the mask image:
cv2.drawContours(inputCopy, contours, -1, (255, 0, 0), 3)

这是结果:

现在,如果您想要非黑色区域的平均 BGR(A) 值,请使用我们获得的二进制掩码并将其作为 mask 传递给 cv2.mean,如下所示:

means = cv2.mean(inputImage, mask=binaryImage)

你得到:

(130.01283431634118, 223.66963836747732, 121.75817119126356, 0.0)