Ejemplo n.º 1
0
def find_color(img_path):
    # load the image and convert it from BGR to RGB so that
    # we can dispaly it with matplotlib
    image = cv2.imread(img_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # show our image
    #plt.figure()
    #plt.axis("off")
    #plt.imshow(image)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters = 3)
    clt.fit(image)

    # build a histogram of clusters and then create a figure
    # representing the number of pixels labeled to each color
    hist = utils.centroid_histogram(clt)
    #print(clt.cluster_centers_)
    bar = utils.plot_colors(hist, clt.cluster_centers_)
    #print("color centroids",clt.cluster_centers_)
    # show our color bart
    plt.figure()
    plt.axis("off")
    plt.imshow(bar)
    plt.show()
Ejemplo n.º 2
0
def color_quantization(image, mask, save_path, num_clusters):
    
    #grab image width and height
    (h, w) = image.shape[:2]
    
    #change the color storage order
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    
    #apply the mask to get the segmentation of plant
    masked_image = cv2.bitwise_and(image, image, mask = mask)
       
    # reshape the image to be a list of pixels
    pixels = masked_image.reshape((masked_image.shape[0] * masked_image.shape[1], 3))
        
    ############################################################
    #Clustering process
    ###############################################################
    # cluster the pixel intensities
    clt = MiniBatchKMeans(n_clusters = num_clusters)
    #clt = KMeans(n_clusters = args["clusters"])
    clt.fit(pixels)

    #assign labels to each cluster 
    labels = clt.fit_predict(pixels)

    #obtain the quantized clusters using each label
    quant = clt.cluster_centers_.astype("uint8")[labels]

    # reshape the feature vectors to images
    quant = quant.reshape((h, w, 3))
    image_rec = pixels.reshape((h, w, 3))
    
    # convert from L*a*b* to RGB
    quant = cv2.cvtColor(quant, cv2.COLOR_RGB2BGR)
    image_rec = cv2.cvtColor(image_rec, cv2.COLOR_RGB2BGR)
    
    # display the images and wait for a keypress
    #cv2.imshow("image", np.hstack([image_rec, quant]))
    #cv2.waitKey(0)
    
    #define result path for labeled images
    result_img_path = save_path + 'cluster_out.png'
    
    # save color_quantization results
    cv2.imwrite(result_img_path,quant)

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

    # remove the background color cluster
    clt.cluster_centers_ = clt.cluster_centers_[1: len(clt.cluster_centers_)]

    #build a histogram of clusters using center lables
    numLabels = utils.plot_centroid_histogram(save_path,clt)

    #create a figure representing the distribution of each color
    bar = utils.plot_colors(hist, clt.cluster_centers_)

    #save a figure of color bar 
    utils.plot_color_bar(save_path, bar)
Ejemplo n.º 3
0
def colourAuto(imPath):

    image = cv2.imread(imPath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters=5)
    clt.fit(image)

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

    #cv2.imshow("bar",  cv2.cvtColor(bar, cv2.COLOR_BGR2RGB))
    print "RETURNED LIST - -------------------------------"
    print "color of the alphabet is %s" % (colorAlpha)
    print "color of the shape is %s" % (colorShape)
    z = easygui.ynbox('Color Detection done', 'Title',
                      ('Continue with Shape', 'Go to manual'))
    print z
    if z == True:
        print "hello"

    else:
        (colorAlpha, colorShape) = colourManual()
        print "---------------------Manual-------------------------"
        print 'colour of alphanumeral is' + colorAlpha, '\ncolor of shape is' + colorShape  #TODO write to .csv file inst

    return colorAlpha, colorShape
def get_top_n_colors(image_path, n_cluster):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # show original image
    # show_image(image)
    image = image.reshape((image.shape[0] * image.shape[1], 3))

    # cluster the pixel intensities
    clt = KMeans(n_clusters=n_cluster)
    clt.fit(image)

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

    # RGB
    #bar = utils.plot_colors(hist, clt.cluster_centers_)
    # show our color bar
    # show_image(bar)

    # show both images
    # plt.show()

    Cluster_center = [[int(elem) for elem in myList]
                      for myList in clt.cluster_centers_]
    Proportion = [round(elem * 100, 2) for elem in hist]

    return zip(Cluster_center, Proportion)
    def RunPro(self):

        myimage = self.path
        mycluster = int((self.spin).get())

        # load the image and convert it from BGR to RGB so that
        # we can dispaly it with matplotlib
        image = cv2.imread(myimage)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

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

        # cluster the pixel intensities
        clt = KMeans(n_clusters=mycluster)
        clt.fit(image)

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

        # show our color bart
        plt.figure()
        plt.axis("off")
        plt.imshow(bar)
        plt.show()
Ejemplo n.º 6
0
def classifyColor(image_color):
    image_color = cv2.cvtColor(image_color, cv2.COLOR_BGR2RGB)
    image_color = image_color.reshape(
        (image_color.shape[0] * image_color.shape[1], 3))

    clt = KMeans(n_clusters=3)
    clt.fit(image_color)

    hist = utils.centroid_histogram(clt)

    d = {}
    for (percent, color) in zip(hist, clt.cluster_centers_):
        p = round(percent, 2)
        colors = [int(color[0]), int(color[1]),
                  int(color[2])]  # R: color[0], G: color[1], B: color[2]
        d[p] = colors

    od = collections.OrderedDict(sorted(d.items(), reverse=True))
    # print(od)
    count = 1
    for percent in od:
        if count > 2: break
        color = od[percent]
        # suppose white or black is background
        if (color[0] < 5 and color[1] < 5
                and color[2] < 5) or (color[0] > 250 and color[1] > 250
                                      and color[2] > 250):
            # print("background")
            continue
        count += 1

        return color
Ejemplo n.º 7
0
    def cluster(self):
        ap = argparse.ArgumentParser()

        image = cv2.imread("photo/final.jpg")
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        plt.figure()
        plt.axis("off")
        plt.imshow(image)

        image = image.reshape((image.shape[0] * image.shape[1], 3))

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

        # show our color bart
        plt.figure()
        plt.axis("off")
        plt.imshow(bar)
        plt.show()
Ejemplo n.º 8
0
def colorPicker(num):
    _img = request.files.get('img', None)

    #: load the image and convert it from BGR to RGB so that
    #: we can dispaly it with matplotlib
    image = np.asarray(bytearray(_img.read()), dtype='uint8')
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

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

    #: cluster the pixel intensities
    clt = KMeans(n_clusters=num)
    clt.fit(image)

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

    result = []
    for color in colors:
        temp = {}
        temp['rgb'] = color
        hexcolor = '#{:02x}{:02x}{:02x}'.format(color[0], color[1], color[2])
        temp['hex'] = hexcolor

        result.append(temp)

    return make_response(jsonify(colors=result))
Ejemplo n.º 9
0
def kmeans(image, clusters):
    # load the image and convert it from BGR to RGB so that
    # we can dispaly it with matplotlib
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # convert to LAB format
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)

    # show our image
    if False:
        plt.figure()
        plt.axis("off")
        plt.imshow(image)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters=clusters)
    clt.fit(image)

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

    def sorted_idx(array):
        return sorted(range(len(array)), key=lambda k: array[k])

    s_hist = []
    s_clusters = []
    discarded = 0.0
    s_discarded = []
    for idx in sorted_idx(hist):
        # Discard any bin that is > 50%
        if hist[idx] > 0.5:
            # Assume top discarded is the background
            if not s_discarded:
                discarded = hist[idx]
                s_discarded = clt.cluster_centers_[idx]
            continue
        s_hist.append(hist[idx])
        s_clusters.append(clt.cluster_centers_[idx])

    # Rescale
    if discarded:
        for i, _ in enumerate(s_hist):
            s_hist[i] /= (1 - discarded)

    #bar = utils.plot_colors(hist, clt.cluster_centers_)
    bar = utils.plot_colors(s_hist, s_clusters)
    # show our color bart
    if False:
        plt.figure()
        plt.axis("off")
        plt.imshow(bar)
        plt.show()

    # Returns: [(percentage, RGB), ...], top discarded RGB
    return OrderedDict(zip(s_hist, s_clusters)), s_discarded
Ejemplo n.º 10
0
def calcKMeans(im):
    #print("Calculating k-means clusters...")
    clt = KMeans(n_clusters=3)
    #print(clt)
    imReshaped = im.reshape((im.shape[0] * im.shape[1], 3))
    clt.fit(imReshaped)

    # build a histogram of clusters and then create a figure
    # representing the number of pixels labeled to each color
    hist = utils.centroid_histogram(clt)
    bar = utils.plot_colors(hist, clt.cluster_centers_)
    return bar
Ejemplo n.º 11
0
def dominantColor(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = image.reshape((image.shape[0] * image.shape[1], 3))
    clt = KMeans(n_clusters=5)
    clt.fit(image)
    hist = utils.centroid_histogram(clt)
    bar = utils.plot_colors(hist, clt.cluster_centers_)

    # show our color bart
    plt.figure()
    plt.axis("off")
    plt.imshow(bar)
    plt.show()
Ejemplo n.º 12
0
def get_kmeans_color(img, count, x, y):
    #t0 = time.time()
    img = img.reshape((img.shape[0] * img.shape[1], 3))
    clt = KMeans(n_clusters = count)
    clt.fit(img)

    hist = utils.centroid_histogram(clt)
    colors = clt.cluster_centers_.astype("uint8").tolist()

    if hist[0] > hist[1]:
        return [(hist[0], colors[0]),
                (hist[1], colors[1])]
    else:
        return [(hist[1], colors[1]),
                (hist[0], colors[0])]
Ejemplo n.º 13
0
def select_image():
    # grab a reference to the image panels
    global panelA, panelB
    path = filedialog.askopenfilename()
    n_clusters = int(e.get())
    if len(path) > 0:
        # load the image from disk, convert it to grayscale, and detect
        # edges in it
        image = cv2.imread(path)
        image2 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        #dinh dang hinh anh thanh 1 danh sach pixel ma tran Mxn,voi 3 mau RGB
        image1 = image2.reshape((image2.shape[0] * image2.shape[1], 3))
        #chinh kich thuoc anh ve 640x380
        image = cv2.resize(image, (640, 380))
        image3 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        km = Kmeans(n_clusters)
        km.fit(image1)
        labels = km.labels
        centroids = km.centroids

        #init_centers=kmeans.kmeans_init_centers(image1,n_clusters)
        #init_labels=np.zeros(image1.shape[0])
        #centroids,labels=kmeans.kmeans(init_centers,init_labels,image1,n_clusters)
        #sap xep danh sach cac pixel
        hist = utils.centroid_histogram(labels)
        edged = utils.plot_colors(hist, centroids)
        #tao hinh anh dung de ve tren plt
        image = Image.fromarray(image3)
        edged = Image.fromarray(edged)

        image = ImageTk.PhotoImage(image)
        edged = ImageTk.PhotoImage(edged)
    if panelA is None or panelB is None:

        panelA = Label(image=image)
        panelA.image = image
        panelA.pack(side="left", padx=10, pady=10)

        panelB = Label(image=edged)
        panelB.image = edged
        panelB.pack(side="right", padx=10, pady=10)

    else:

        panelA.configure(image=image)
        panelB.configure(image=edged)
        panelA.image = image
        panelB.image = edged
Ejemplo n.º 14
0
def km(path):
    img = cv2.imread(path)
    # reshape the image to be a list of pixels
    image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    image = img.reshape((image.shape[0] * image.shape[1], 3))

    # cluster the pixel intensities
    clt = KMeans(n_clusters=args["clusters"])
    clt.fit(image)

    #count the number of pixels that are assigned to each cluster
    hist = utils.centroid_histogram(clt)
    # the figure that visualizes the number of pixels assigned to each cluster
    bar = utils.plot_colors(hist, clt.cluster_centers_)

    return bar
Ejemplo n.º 15
0
def kmeans_image(image_path, clt):
    image = cv2.imread(image_path)
    # TODO CHECK IF OK TO REMOVE? Matlab needs rbg. but order might be different
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image = image.reshape((image.shape[0] * image.shape[1], 3))

    # cluster the pixel intensities
    clt.fit(image)

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

    return percentage_color_list
Ejemplo n.º 16
0
def colourAutoSubProcess(imagePath):
    # load the image and convert it from BGR to RGB so that we can dispaly it with matplotlib
    image = cv2.imread(imagePath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters=5)
    clt.fit(image)

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

    return (bar, sorted_D, l1, l2)
Ejemplo n.º 17
0
def get_dominant_colors(image, path):
    # load the image and convert it from BGR to RGB so that
    # we can dispaly it with matplotlib
    image = cv2.imread(path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # # show our image
    # plt.figure()
    # plt.axis("off")
    # plt.imshow(image)


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


    # cluster the pixel intensities
    clt = KMeans(n_clusters = 3) # RGB values of HSV picture
    clt.fit(image)


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

    max_color = hist.max()

    histogram_size = hist.__len__()
    for i in range(0,histogram_size):
        if hist[i] >= max_color:
            dominant_color_index = i

    h, s, v = clt.cluster_centers_[dominant_color_index]
    # h, s, v = rgb_to_hsv(r, g, b)


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

    return h, s, v
Ejemplo n.º 18
0
def coulor_Kmeans(xmin,ymin,xmax,ymax,image,clusters):
    image_new=image[xmin:xmax,ymin:ymax,:]
    image_new = image_new.reshape((image_new.shape[0] * image_new.shape[1], 3))

# cluster the pixel intensities
    clt = KMeans(n_clusters = clusters)
    clt.fit(image_new)

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

# show our color bart
    plt.figure()
    plt.axis("off")
    plt.imshow(bar)
    plt.show()
    return clt.cluster_centers_
def bounding_box_dominant_colour(img, x1, y1, w, h):
    # given a bounding box definitions and an image, return the dominant colour for that box via
    # k-means clustering

    roi = img[int(y1):int(y1 + h), int(x1):int(x1 + w)]

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters=5)
    clt.fit(roi)

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

    max_cluster = np.argmax(hist)
    rgb = clt.cluster_centers_[max_cluster].astype(int)

    return get_colour_name(rgb)
Ejemplo n.º 20
0
def kmeans_image_show(image_path, clusters=3):
    pass
    # construct the argument parser and parse the arguments
    # ap = argparse.ArgumentParser()
    # ap.add_argument("-i", "--image", required = True, help = "Path to the image")
    # ap.add_argument("-c", "--clusters", required = True, type = int, help = "# of clusters")
    # args = vars(ap.parse_args())
    #
    # load the image and convert it from BGR to RGB so that
    # we can display it with matplotlib
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # show our image
    plt.figure()
    plt.axis("off")
    plt.imshow(image)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters = clusters)
    clt.fit(image)

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

    print percentage_color_list
    print percentage_color_list[0][1][0]

    bar = utils.plot_colors(hist, clt.cluster_centers_)

    # show our color bart
    plt.figure()
    plt.axis("off")
    plt.imshow(bar)
    plt.show()
Ejemplo n.º 21
0
def color_kmeans(src_bg_im, n_colors=3):
    """
    compute k-means color clustering
    :param src_bg_im:
    :param n_colors: number of object's color
    :return: histogram, colors and colors' stddev
    """
    src_bg_im = resize_if_necessary(src_bg_im, MAX_SAMPLE_COLS)

    rows, cols, channels = src_bg_im.shape
    img_lab = cv2.cvtColor(src_bg_im, cv2.COLOR_BGR2LAB)
    img_lab = img_lab.reshape((rows * cols, channels))

    # print 'src_im:', rows, cols, src_im.dtype
    # print 'img_lab:', img_lab.shape, img_lab.dtype

    # Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 8, 1.0)
    # Set flags (Just to avoid line break in the code)
    flags = cv2.KMEANS_RANDOM_CENTERS

    clusters = n_colors + 2
    compactness, labels, centroids = cv2.kmeans(np.float32(img_lab), clusters,
                                                None, criteria, 10, flags)

    hist = utils.centroid_histogram(labels)
    hist_colors = [(p, c) for (p, c) in zip(hist, centroids)]
    hist_colors = sorted(hist_colors, key=lambda pc: pc[0], reverse=True)

    stddev = np.sqrt(compactness / (rows * cols))
    filtered_colors = [
        pc for pc in hist_colors
        if pc[1][0] > MIN_LIGHT_VALUE and pc[1][0] < MAX_LIGHT_VALUE
    ]
    if len(filtered_colors) < n_colors:
        filtered_colors = hist_colors

    return [colors[0] for colors in filtered_colors
            ], [colors[1] for colors in filtered_colors], stddev
Ejemplo n.º 22
0
def colorCluster(img, k, v_threshold):
    # load the image and convert it from BGR to RGB so that
    # we can dispaly it with matplotlib
    image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters=k)
    clt.fit(image)

    hist = utils.centroid_histogram(clt)
    zipped = zip(hist, clt.cluster_centers_)

    max_var_color = None
    max_var = None
    hasblack = None

    for percent, color in zipped:
        variance = np.var(color)
        if variance < v_threshold:
            variance = 0

        if max_var is None or max_var < variance:
            max_var = variance
            max_var_color = color

        luma = 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2]

        # using luma values to find white and black

        if luma < 20:
            hasblack = color

    if max_var_color is not None and max_var != 0:
        return max_var_color

    return hasblack
def getDominantColor(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

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

    # cluster the pixel intensities
    clt = KMeans(n_clusters=3)
    clt.fit(image)

    hist = utils.centroid_histogram(clt)

    dominantColorRGB = clt.cluster_centers_[np.argmax(hist)]
    print 'dominant color rgb: ', dominantColorRGB
    dominantColorRGB = dominantColorRGB.astype('uint8')
    dominantColorRGB = np.reshape(dominantColorRGB, (1, 1, 3))
    dominantColorLAB = cv2.cvtColor(dominantColorRGB, cv2.COLOR_RGB2LAB)
    dominantColorLAB = dominantColorLAB[0][0].astype('float64')
    dominantColorLAB[0] *= 100 / 255.0
    dominantColorLAB[1] -= 128
    dominantColorLAB[2] -= 128

    return dominantColorLAB
Ejemplo n.º 24
0
def predict_color(image):
    print("predict_color")
    # extract color
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = image.reshape((image.shape[0] * image.shape[1], 3))
    clt.fit(image)
    hist = utils.centroid_histogram(clt)

    d = {}
    for (percent, color) in zip(hist, clt.cluster_centers_):
        p = round(percent, 2)
        colors = [int(color[0]), int(color[1]), int(color[2])] # R: color[0], G: color[1], B: color[2]
        d[p] = colors

    od = collections.OrderedDict(sorted(d.items(), reverse=True))
    # print(od)
    R = 0
    G = 0
    B = 0
    count = 1 # 주석?
    for percent in od:
        if count > 2: break # 주석?
        color = od[percent]
        # suppose pure white or pure black is background
        if (color[0] < 5 and color[1] < 5 and color[2] < 5) or (color[0] > 250 and color[1] > 250 and color[2] > 250):
            # print("background")
            continue
        # print(str(count) + ": " + "R ("+str(color[0])+"), G ("+str(color[1])+"), B ("+str(color[2])+")")
        else:
            R = color[0]
            G = color[1]
            B = color[2]
            break
        count+=1 # 주석?
    print("R: " + str(R) + ", "+"G: " + str(G) + ", "+"B: " + str(B))
    return R,G,B
Ejemplo n.º 25
0
import utils as ut
import cv2

img = '/home/brito/Documentos/Dev/tcc/img/f1.jpeg'
img = cv2.imread(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
rect = (430, 196, 800, 310)

img = ut.black_back(img, rect)
img = img.reshape((img.shape[0] * img.shape[1], 3))

# k means determine k
distortions = []
hist_all = []
K = range(1, 10)
for k in K:
    kmeanModel = KMeans(n_clusters=k).fit(img)
    kmeanModel.fit(img)
    hist_all.append(ut.centroid_histogram(kmeanModel))
    distortions.append(
        sum(
            np.min(cdist(img, kmeanModel.cluster_centers_, 'euclidean'),
                   axis=1)) / img.shape[0])

# Plot the elbow
plt.plot(K, distortions, 'bx-')
plt.xlabel('k')
plt.ylabel('Distortion')
plt.title('The Elbow Method showing the optimal k')
plt.show()
# we can dispaly it with matplotlib
image = cv2.imread(args["image"])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# show our image
plt.figure()
plt.axis("off")
plt.imshow(image)

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

# cluster the pixel intensities
clt = KMeans(n_clusters=args["clusters"])
clt.fit(image)

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

bar[0][0][1] = 255
domColor = bar[0][0]
print(domColor)

# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
Ejemplo n.º 27
0
	help = "# of clusters")
args = vars(ap.parse_args())

# load the image and convert it from BGR to RGB so that
# we can dispaly it with matplotlib
image = cv2.imread(args["image"])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# show our image
plt.figure()
plt.axis("off")
plt.imshow(image)

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

# cluster the pixel intensities
clt = KMeans(n_clusters = args["clusters"])
clt.fit(image)

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

# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
def color_quantization(image, mask, save_path, num_clusters):
    
    #grab image width and height
    (h, w) = image.shape[:2]
    
    #change the color storage order
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)

    #apply the mask to get the segmentation of plant
    masked_image_BGR = cv2.bitwise_and(image, image, mask = mask)
    
    #define result path for labeled images
    result_img_path = save_path + 'masked.png'
    cv2.imwrite(result_img_path, masked_image_BGR)
    
    # convert the image from the RGB color space to the L*a*b*
    # color space -- since we will be clustering using k-means
    # which is based on the euclidean distance, we'll use the
    # L*a*b* color space where the euclidean distance implies
    # perceptual meaning
    #masked_image = cv2.cvtColor(masked_image_BGR, cv2.COLOR_BGR2LAB)
    masked_image = cv2.cvtColor(masked_image_BGR, cv2.COLOR_BGR2RGB)
    
    #reshape the image to be a list of pixels
    pixels = masked_image.reshape((masked_image.shape[0] * masked_image.shape[1], 3))
    
    ############################################################
    #Clustering process
    ###############################################################
    # cluster the pixel intensities
    clt = MiniBatchKMeans(n_clusters = num_clusters)
    #clt = KMeans(n_clusters = args["clusters"])
    clt.fit(pixels)

    #assign labels to each cluster 
    labels = clt.fit_predict(pixels)

    #obtain the quantized clusters using each label
    quant = clt.cluster_centers_.astype("uint8")[labels]
    
    #reshape the feature vectors to images
    quant = quant.reshape((h, w, 3))
    image_rec = pixels.reshape((h, w, 3))
    
    #convert from L*a*b* to RGB
    quant = cv2.cvtColor(quant, cv2.COLOR_RGB2BGR)
    #quant = cv2.cvtColor(quant, cv2.COLOR_LAB2BGR)
    
    #define result path for labeled images
    result_img_path = save_path + 'cluster_out.png'
    
    # save color_quantization results
    cv2.imwrite(result_img_path, quant)
    

    counts = Counter(labels)
    # sort to ensure correct color percentage
    counts = dict(sorted(counts.items()))
    
    center_colors = clt.cluster_centers_

    # We get ordered colors by iterating through the keys
    ordered_colors = [center_colors[i] for i in counts.keys()]
    hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
    rgb_colors = [ordered_colors[i] for i in counts.keys()]

    #print(hex_colors)
    
    index_bkg = [index for index in range(len(hex_colors)) if hex_colors[index] == '#000000']
    
    #print(index_bkg[0])

    #print(counts)
    #remove background color 
    del hex_colors[index_bkg[0]]
    del rgb_colors[index_bkg[0]]
    
    # Using dictionary comprehension to find list 
    # keys having value . 
    delete = [key for key in counts if key == index_bkg[0]] 
  
    # delete the key 
    for key in delete: del counts[key] 
   
    fig = plt.figure(figsize = (6, 6))
    plt.pie(counts.values(), labels = hex_colors, colors = hex_colors)

    #define result path for labeled images
    result_img_path = save_path + 'pie_color.png'
    plt.savefig(result_img_path)
        
    #build a histogram of clusters and then create a figure representing the number of pixels labeled to each color
    hist = utils.centroid_histogram(clt)

    #remove the background color cluster
    clt.cluster_centers_ = np.delete(clt.cluster_centers_, index_bkg[0], axis=0)
    
    #build a histogram of clusters using center lables
    numLabels = utils.plot_centroid_histogram(save_path,clt)

    #create a figure representing the distribution of each color
    bar = utils.plot_colors(hist, clt.cluster_centers_)

    #save a figure of color bar 
    utils.plot_color_bar(save_path, bar)
    
    
    return rgb_colors
Ejemplo n.º 29
0
        clusters = KMeans(n_clusters=num)
        clusters.fit(image_pixels)

        # After the call to fit, the key information is contained
        # in  clusters.cluster_centers_ :
        # count = 0
        # for center in clusters.cluster_centers_:
        #     print("Center #", count, " == ", center)
        #     # note that the center's values are floats, not ints!
        #     center_integers = [int(p) for p in center]
        #     print("   and as ints:", center_integers)
        #     count += 1

        # build a histogram of clusters and then create a figure
        # representing the number of pixels labeled to each color
        hist = utils.centroid_histogram(clusters)
        bar = utils.plot_colors(hist, clusters.cluster_centers_)
        bars.append(bar)
        title = str(num) + " means"
        titles.append(title)

    # in the first figure window, show our image
    # plt.figure()
    # plt.axis("off")
    # plt.imshow(image)

    # in the second figure window, show the pixel histograms
    #   this starter code has a single value of k for each
    #   your task is to vary k and show the resulting histograms
    # this also illustrates one way to display multiple images
    # in a 2d layout (fig == figure, ax == axes)
Ejemplo n.º 30
0
    image_data = cv2.imread(image)
    # image_data = cv2.cvtColor(image_data, cv2.COLOR_BGR2RGB)
    image_data = cv2.cvtColor(image_data, cv2.COLOR_BGR2RGB)

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

    # cluster the pixel intensities
    db = KMeans(n_clusters=cluster)
    db.fit(image_data)

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

    # reorganize colors
    hist_color = zip(hist, db.cluster_centers_)
    hist_out, color = zip(*hist_color)

    # print hist_out, color
    # set up dictionary and list to sort colors
    intensity_dict = {}
    color_sorted_by_int = []

    # convert RGB to intensity
    for hist, col in hist_color:
        # get intensity values
        intensity = (0.299 * col[0] + 0.587 * col[1] + 0.114 * col[2])
cv2.imshow('ycrcb', image);
cv2.waitKey(0);

# reshape image to metrix N x 3
imageReshaped = image.reshape((-1, 3))
# change data in array from uint8 to float32
imageReshaped = np.float32(imageReshaped)

# rule the iteration termination
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# number of cluster
K = 8
ret, label, center = cv2.kmeans(imageReshaped, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

# find mean color range and percent of color in image
hist = utils.centroid_histogram(center, label)
bar = utils.plot_colors(hist, center)

# convert back to uint8 and reshape image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((image.shape))

# print color and percent in image
for(percent, color) in zip(hist, center):
    print "color(", color, ") = ", percent*100, "%"

plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
Ejemplo n.º 32
0
print 'image.ndim:{}, img_lab.ndim:{}'.format(image.ndim, img_lab.ndim)

# show our image
plt.figure()
plt.axis("off")
plt.imshow(image)

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

# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Set flags (Just to avoid line break in the code)
flags = cv2.KMEANS_RANDOM_CENTERS

n_clusters = args.clusters
compactness, labels, centers = cv2.kmeans(np.float32(img_lab), n_clusters,
                                          None, criteria, 10, flags)

# build a histogram of clusters and then create a figure
# representing the number of pixels labeled to each color
hist = utils.centroid_histogram(labels)
bar = utils.plot_colors_lab(hist, centers)

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