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

时间:2019-05-15 16:12:48

标签: python opencv 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)

是我当前正在使用的代码

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

1 个答案:

答案 0 :(得分:1)

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)
相关问题