コード例 #1
0
def rgb_weighted_average(target_image, target_colors, reference_colors):
	"""
	Recolors target image by performing a weighted average over color
	differences with reference image using preprocessed cluster centers
	as weights.
	"""

	Color.load_cluster()

	rate = 0
	rate_count = 1

	color_weights_total = np.array([0., 0., 0.])

	for color in ["red", "blue"]:
		if color in target_colors and color in reference_colors:
			color_index = Color.labels.index(color)
			cluster_color = Color(Color.clusters.cluster_centers_[color_index], Color.format).array("RGB")

			color_weights = cluster_color

			color_weights_total += color_weights

			rate += color_weights * (reference_colors[color].array("RGB") - target_colors[color].array("RGB"))
	
	rate = rate / color_weights_total

	recolored_image = target_image + rate

	
	return recolored_image
コード例 #2
0
def rgb_log_weighted_average(target_image, target_colors, reference_colors):
	"""
	Computes a log weighted average over reference-target color ratio
	in RGB format using preprocessed clusters centers as weights.
	"""

	Color.load_cluster()

	rate = 0
	rate_count = 1

	color_weights_total = np.array([0., 0., 0.])

	for color in ["red", "blue"]:
		if color in target_colors and color in reference_colors:
			color_index = Color.labels.index(color)
			cluster_color = Color(Color.clusters.cluster_centers_[color_index], Color.format).array("RGB")

			color_weights = cluster_color

			color_weights_total += color_weights

			rate += color_weights * np.log(reference_colors[color].array("RGB") / target_colors[color].array("RGB"))
	
	rate = np.exp(rate / color_weights_total)

	recolored_image = target_image * rate

	
	return recolored_image
コード例 #3
0
def main(plot_format):
    color_cluster_data = None

    with open("data/lab_cluster_colors.json") as input_file:
        color_cluster_data = json.load(input_file)

    colors = np.array(color_cluster_data["colors"])

    color_format = color_cluster_data["format"]
    color_labels = color_cluster_data["labels"]
    clusters = KMeans(
        n_clusters=color_cluster_data["number_of_clusters"],
        random_state=color_cluster_data["random_seed"]).fit(colors)

    colors = np.array(
        [Color(color, color_format).array(plot_format) for color in colors])

    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(colors[:, 0],
               colors[:, 1],
               colors[:, 2],
               c=np.array([
                   color_labels[clusters.labels_[i]]
                   for i in range(len(colors))
               ]))

    ax.set_xlabel(plot_format[0])
    ax.set_ylabel(plot_format[1])
    ax.set_zlabel(plot_format[2])

    plt.show()
コード例 #4
0
def biggest_colored_cluster(clusters):
    """
	Select the mean color of the biggest cluster not classified as white 
	using previous color observations as a reference.
	"""

    mean_count = [0] * len(clusters.cluster_centers_)

    for label in clusters.labels_:
        mean_count[label] += 1

    indices = [index for index in range(len(mean_count))]

    indices.sort(key=lambda index: -mean_count[index])

    for index in indices:
        if Color(clusters.cluster_centers_[index], "BGR").label() != "white":
            break
    else:
        index = indices[0]

    return index
コード例 #5
0
def main(directory_path):
    # Data
    csv_data = []

    for path, subdirs, files in os.walk(directory_path):
        for filename in files:
            input_path = os.path.join(path, filename)

            print(input_path)

            image = cv2.imread(input_path)

            contours = detect_objects(image)

            image_number = 0
            for c in contours:
                x, y, w, h = cv2.boundingRect(c)

                if filter_out_of_range and (w < 100 or h < 100):
                    continue

                image_number += 1

                valid_points = choose_valid_points(x, y, w, h)

                # Group selected points into clusters
                clusters = KMeans(
                    n_clusters=number_of_clusters, random_state=0).fit(
                        np.array([image[p[0]][p[1]] for p in valid_points]))

                # Select color from clustered points
                index = choose_color(clusters)

                object_color = Color(clusters.cluster_centers_[index], "BGR")
                color_label = object_color.label()

                print("  Object", image_number, "color: ",
                      object_color.array("LAB"))

                cluster_points = []

                for i in range(len(valid_points)):
                    if clusters.labels_[i] == index:
                        cluster_points.append(
                            Color.transform(image[valid_points[i][0],
                                                  valid_points[i][1]],
                                            "BGR",
                                            to="LAB"))

                average = np.average(cluster_points, axis=0)
                standard_deviation = np.std(cluster_points, axis=0)

                print("    Average: " + str(average))
                print("    Standard deviation: " + str(standard_deviation))

                csv_data.append({
                    "name": input_path,
                    "object_id": image_number,
                    "average": average,
                    "standard_deviation": standard_deviation,
                    "color_label": color_label
                })

    with open("data/color_data.csv", "w") as csv_file:
        field_names = [
            "name", "object_id", "average", "standard_deviation", "color_label"
        ]
        writer = csv.DictWriter(csv_file, fieldnames=field_names)

        writer.writeheader()

        for row in csv_data:
            writer.writerow(row)
コード例 #6
0
    for c in contours:
        x, y, w, h = cv2.boundingRect(c)

        if w < 100 or h < 100:
            continue

        valid_points = choose_valid_points(x, y, w, h)
        valid_colors = np.array([image[p[0], p[1]] for p in valid_points])

        # Group selected points into clusters
        clusters = KMeans(n_clusters=number_of_clusters,
                          random_state=0).fit(valid_colors)

        colors.append([
            Color(color, "BGR").array(clustering_format)
            for color in clusters.cluster_centers_
        ])

lab_colors = np.concatenate(np.array(colors), axis=0)

clusters = KMeans(n_clusters=number_of_clusters,
                  random_state=random_state).fit(lab_colors)
print(clusters.cluster_centers_)

labels = ["red", "blue", "green", "white"]
color_labels = []

for cluster_center in clusters.cluster_centers_:
    print("Labels (red, blue, green or white):")
コード例 #7
0
def get_colors(
	image,
	contours,
	number_of_clusters=3,
	choose_valid_points=choose_valid_points.ellipse,
	choose_color=choose_color.biggest_colored_cluster,
	filter_out_of_range=True,
	draw_box=False,
	draw_points=False,
	stats_format=None
):
	"""
	Calculates colors in IMAGE from each object in CONTOURS.

	Arguments:
	image -- image from which objects are recognized.
	contours -- list of contours of detected objects.
	number_of_clusters -- used in k-means clustering.
	choose_color -- function to obtain the representative color of an object.
	choose_valid_points -- function to obtain the set of valid points from an object.
	filter_out_of_range -- if True, prevents small objects to be considered.
	draw_box -- if True, draw box in image.
	draw_points -- if True, paint valid points in image.
	stats_format -- prints object stats in the given format. If None is given, stats are not printed.

	Returns
	image_color_data -- dictionary
		object_colors -- array of Color objects from the objects detected in the image
		image_colors -- dictionary of colors (red, blue, etc.) associated with a Color object
	"""

	print_stats = stats_format is not None
	
	if not print_stats:
		stats_format = "LAB"

	lab_colors = []

	for c in contours:
		x, y, w, h = cv2.boundingRect(c)

		if filter_out_of_range and (w < 100 or h < 100):
			continue

		valid_points = choose_valid_points(x, y, w, h)
	
		# Group selected points into clusters
		clusters = KMeans(n_clusters=number_of_clusters, random_state=0).fit(np.array([image[p[0]][p[1]] for p in valid_points]))
	
		# Select index of cluster
		index = choose_color(clusters)
		object_color = Color(clusters.cluster_centers_[index], "BGR")

		lab_colors.append(object_color)


		# The following lines 
		box_color = [36, 255, 12]
	
		if draw_box:
			cv2.rectangle(image, (x, y), (x + w, y + h), box_color, 2)
	
		if draw_points or print_stats:
			cluster_points = []
	
			for i in range(len(valid_points)):
				if clusters.labels_[i] == index:
					cluster_points.append(Color.transform(image[valid_points[i][0], valid_points[i][1]], "BGR", to=stats_format))
	
					if draw_points:
						image[valid_points[i][0], valid_points[i][1]] = box_color
	
			if print_stats:
				print(object_color.to(stats_format))
				print("    Average: " + str(np.average(cluster_points,axis=0)))
				print("    Standard deviation: " + str(np.std(cluster_points,axis=0)))
	
	image_colors = {}

	lab_colors = np.array(lab_colors)

	for lab_color in lab_colors[::-1]:
		if lab_color.label() in ["red", "blue"]:
			image_colors[lab_color.label()] = lab_color
	
	image_color_data = {
		"object_colors": lab_colors,
		"image_colors": image_colors
	}


	return image_color_data