Удаление цвета фона из анализа доминирующих цветов изображения (python, OpenCV) - PullRequest
0 голосов
/ 12 октября 2018

Я работаю с отличным кодом (это не мой!) Из https://www.pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/.

Я пытаюсь понять, что при нанесении цветов я хочу удалить определенные -в этом случае я хочу вырезать / не измерять белый фон игрушки при построении гистограммы.В других случаях при работе с прозрачным фоном он вытягивает серый / белый проверенный фон (например, https://i.stack.imgur.com/WLjsK.png), поэтому я бы хотел переместить оба этих "цвета".

Может кто-нибудь подтолкнуть меня кправильный способ решения этой проблемы, пожалуйста?

Большое спасибо !!

import cv2
import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt

!wget "https://www.beatrix-potter-shop.co.uk/app/uploads/2017/07/PO1424_Benjamin.jpg"

# Load the image
image = cv2.imread("PO1424_Benjamin.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 

# Resize it for efficiency (color ratios are the same)
h, w, _ = image.shape
w_new = int(100 * w / max(w, h) )
h_new = int(100 * h / max(w, h) )

image = cv2.resize(image, (w_new, h_new));

# Step 1: Clustering colours with K-Means
from sklearn.cluster import KMeans

# Reshape the image to be a list of pixels
image_array = image.reshape((image.shape[0] * image.shape[1], 3))

# Clusters the pixels
clt = KMeans(n_clusters = 7)
clt.fit(image_array)

# By Adrian Rosebrock
def centroid_histogram(clt):
 # grab the number of different clusters and create a histogram
 # based on the number of pixels assigned to each cluster
 numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
 (hist, _) = np.histogram(clt.labels_, bins = numLabels)

 # normalize the histogram, such that it sums to one
 hist = hist.astype("float")
 hist /= hist.sum()

 # return the histogram
 return hist

# Finds how many pixels are in each cluster
hist = centroid_histogram(clt)

# Sort the clusters according to how many pixel they have
zipped = list(zip(hist, clt.cluster_centers_))
zipped.sort(reverse=True, key=lambda x : x[0])
hist, clt.cluster_centers = zip(*zipped)

def plot_colors(hist, centroids):
    # initialize the bar chart representing the relative frequency
    # of each of the colors
    bar = np.zeros((50, 300, 3), dtype = "uint8")
    startX = 0

    # loop over the percentage of each cluster and the color of
    # each cluster
    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
            color.astype("uint8").tolist(), -1)
        startX = endX

    # return the bar chart
    return bar

# build a histogram of clusters and then create a figure
# representing the number of pixels labeled to each color
hist = centroid_histogram(clt)
bar = plot_colors(hist, clt.cluster_centers_)

# show our color bart
plt.figure()
plt.axis("on")
plt.imshow(bar)
plt.show()
...