![](/img/trans.png)
[英]How to extract the largest connected component using OpenCV and Python?
[英]Taking the largest component of connected components with OpenCV in python
我有一些帶有 alpha 通道的葉子照片 - 背景 alpha 通道為 0,照片中的葉子像素 alpha 通道為 255。
我想將圖像分離為連接的組件。 然后取大連接組件。 為了像紅色標記一樣擦除污垢。 這是我在這里談論的圖像:葉子圖像
這是我當前的代碼:
def remove_pixels(image_path, img_file_output_path):
img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
alpha = img[:, :, 3]
alpha = cv2.threshold(alpha, 0, 255, cv2.THRESH_BINARY)[1]
num_labels, labels_im = cv2.connectedComponents(alpha,connectivity=4)
new_img = np.zeros(img.shape)
largest_label = 1 + np.argmax(labels_im[1:, cv2.CC_STAT_AREA])
h, w = labels_im.shape
for i in range(h*w):
x = i // w
y = i % w
if labels_im[x,y] == largest_label:
new_img[x,y] = img[x,y]
cv2.imwrite(img_file_output_path, new_img)
它不起作用,非常感謝任何幫助。
謝謝:)
-------------------------------------------------
這是我的新代碼:
def remove_pixels(image_path, img_file_output_path):
img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
alpha = img[:, :, 3]
contours = cv2.findContours(alpha, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
# draw white filled contour on black background to use as new alpha channel
new_alpha = np.zeros_like(alpha)
new_alpha = cv2.drawContours(new_alpha, [big_contour], 0, 255, -1)
# put new_alpha into alpha channel of img
new_img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
new_img[:, :, 3] = new_alpha
cv2.imwrite(img_file_output_path, new_img)
和圖片:新圖片
這是 Python/OpenCV 中的一種方法。
- Read the input
- Threshold on white and invert so that the leaf, etc is white on black background
- Get the contours
- Filter the contours on area to keep only the largest
- Draw a white filled contour on a black background using the largest contour
- Put that image into the alpha channel of the input
- Save the result
輸入:
import cv2
import numpy as np
# load image
img = cv2.imread('leaf3.jpg')
# threshold on white and invert
thresh = cv2.inRange(img, (220,220,220), (255,255,255))
thresh = 255 - thresh
# get the largest contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
# draw white filled contour on black background to use as new alpha channel
new_alpha = np.zeros_like(thresh)
new_alpha = cv2.drawContours(new_alpha, [big_contour], 0, 255, -1)
# put new_alpha into alpha channel of img
new_img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
new_img[:, :, 3] = new_alpha
# save result
cv2.imwrite("leaf3_alpha_cleaned.png", new_img)
結果:
可選 - 將背景設置為白色而不是透明。
# make background white
new_img2 = img.copy()
new_img2[new_alpha==0] = (255,255,255)
cv2.imwrite("leaf3_alpha_cleaned2.png", new_img2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.