opencv 我有一个简单的灰色热图,我怎样才能得到重区域?

r1zhe5dt  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(121)

我有一个简单的灰色热图,如

重的地方怎么办?我是一个新来处理图像。_, thresholded = cv2.threshold(gray_image, thresh, 255, cv2.THRESH_BINARY)
无论我设置什么阈值,它仍然覆盖阈值中的几乎每一个彩色像素。
在那之后,我想我可能错误地理解了‘cv2. threshold‘,所以我尝试了_, thresholded = cv2.threshold(gray_image, 0, tresh, cv2.THRESH_BINARY),然后我什么也没有得到。

quhf5bfb

quhf5bfb1#

cv2.threshold不适用于白色背景,我们可以反转极性来创建黑色背景。
我们可以使用thresh = 254,并得到白色的输出。
更有用的解决方案是在使用cv2.threshold之前反转极性(反转白色)。
假设gray_imagedtypenp.uint8,那么白色等于255,黑色等于0
反转极性:inv_gray_image = 255 - gray_image的数据。
代码示例:

import cv2
import numpy as np

gray_image = cv2.imread('gray_image.jpg', cv2.IMREAD_GRAYSCALE)  # Read image in grayscale format

# Invert black and white before applying the threshold
inv_gray_image = 255 - gray_image

thresh = 1  # 1 is just an example - we may use thresh = 100...

_, thresholded = cv2.threshold(inv_gray_image, thresh, 255, cv2.THRESH_BINARY)

cv2.imwrite('thresholded.png', thresholded)  # Save image for testing

字符串
thresholded


的数据
为了找到面积,我们可以使用cv2.findContours,并找到最大轮廓的边界矩形。
范例:

import cv2
import numpy as np

gray_image = cv2.imread('gray_image.jpg', cv2.IMREAD_GRAYSCALE)  # Read image in grayscale format

# Invert black and white before applying the threshold
inv_gray_image = 255 - gray_image  # Valid if gray_image.dtype is uint8
# inv_gray_image = np.iinfo(gray_image.dtype).max - gray_image

thresh = 1

_, thresholded = cv2.threshold(inv_gray_image, thresh, 255, cv2.THRESH_BINARY)

contours = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]  # Find contours
c = max(contours, key=cv2.contourArea)  # Find largest contour

x, y, w, h = cv2.boundingRect(c)  # Get the bounding rectangle
bgr_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR)  # Convert to BGR for drawing colored rectangle
cv2.rectangle(bgr_image, (x, y), (x + w, y + h), (0, 255, 0), 3)  # Draw green rectangle.
cv2.imwrite('bgr_image.png', bgr_image)  # Save image for testing


输出量:


相关问题