python - 如何使用opencv将具有透明背景的图像更改为白色背景

标签 python opencv contour

我正在尝试在 opencv 中定位轮廓,并使用具有透明背景的图像。将图像加载到内存并显示图像后,透明背景已重新着色为围绕图片焦点的黑白矩形。

image = cv.imread('C:/Users/H/Desktop/overhead.png')

cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.imshow('image', image)
cv.waitKey(0)

是我目前使用的代码

图像周围没有黑色像素,而是有几个大的白色 block (被检测为轮廓)。

最佳答案

Convert White Pixels to Black in OpenCV python

我找到了合适的解决方案。

但是现在没有检测到右上角的 ~ 圆形。找到所有 3 个矩形。 tresh

gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
blurred = cv.GaussianBlur(gray, (5, 5), 0)
thresh = cv.threshold(blurred, 103, 255, cv.THRESH_BINARY)[1]

cnts = cv.findContours(thresh.copy(), cv.RETR_EXTERNAL,
cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# loop over the contours
for c in cnts:
# compute the center of the contour
M = cv.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# draw the contour and center of the shape on the image
cv.drawContours(image, [c], -1, (0, 255, 0), 2)
cv.circle(image, (cX, cY), 7, (255, 255, 255), -1)
cv.putText(image, "center", (cX - 20, cY - 20),
cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

# show the image
cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.imshow('image', image)
cv.waitKey(0)

关于python - 如何使用opencv将具有透明背景的图像更改为白色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56153632/

相关文章:

python - 如果每行包含不同数量的字段(数量很大),如何正确读取 csv 文件?

python - cv2.connectedComponents 无法正常工作

python - NSInvalidArgumentException Matplotlib OS X

python - Python中命名的内存映射文件?

opencv - 从颜色形状中检测轮廓点

python 3.7.4 : 're.error: bad escape\s at position 0'

python - 在 python 中模拟类似文件的行为

python - 我可以部署什么样的图像处理技术来去除人眼图像中的睫毛和眉毛?

python - 为什么 pyplot.contour() 要求 Z 是二维数组?

Python 默认记录 exc_info