The following function adjust the color values in grayscale (256) manga. It is based on the fact that manga is originally black ink on white paper so most pixels should be either 0 or 255. The function works for most images but some manga images have mostly light gray tones and in these cases it makes the image to dark. Improve this. List several options on how to do it. Python 3.12 Code: def adjust_grayscale_values(img: np.ndarray) -> tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Round to nearest integer and then convert to uint8
adjusted = np.rint(adjusted).astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error_message(f"Error adjusting values for image: {e}")
return img, 0, 255
Assistant
Improving the adjust_grayscale_values function while addressing cases where the image contains mostly light gray tones involves several potential approaches. Here are some strategies you could adopt:
1. Adaptive Histogram Equalization (CLAHE)
Description: Instead of simple histogram adjustments, use Contrast Limited Adaptive Histogram Equalization (CLAHE). CLAHE adjusts the contrast of each region of the image.
Implementation:
Use OpenCV's CLAHE implementation:
python
import cv2
def apply_clahe(img: np.ndarray) -> np.ndarray:
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
return clahe.apply(img)
# In your function, apply CLAHE before returning
adjusted = apply_clahe(adjusted)
return adjusted, modal_black, modal_white
2. Adaptive Scaling Based on Image Statistics
Description: Use statistical measures (mean and standard deviation) to adjust the image contrasts adaptively.
Description: Implement a user-defined or dynamically calculated factor for situations with predominately light tones.
Implementation:
python
User
how to determin black pixels in an grayscale manga if there not perfect black (0)
Assistant
Determining black pixels in a grayscale manga where blacks are not perfectly zero can be challenging, especially due to the variability in scanning and printing. However, you can define a threshold below which you consider pixels to be "black." Here's how you can do it:
Steps to Determine Black Pixels in Grayscale Manga
Histogram Analysis:
Analyze the image histogram to understand the distribution of pixel intensities. Look for any significant peaks at the lower end of the intensity spectrum, which can indicate clusters of dark pixels.
Thresholding:
Define a threshold value. Any pixel below this threshold can be considered as "black." The threshold can be determined based on the histogram analysis or manually chosen.
Example: If the darkest areas appear around intensity 30 instead of 0, the threshold might be set at 30 or 40.
Adaptive Thresholding:
Use methods like adaptive thresholding that take local region characteristics into account, which is helpful if lighting conditions vary across the image.
OpenCV’s adaptive thresholding is useful in such cases.
Clustering Techniques:
Use k-means clustering to classify pixels into distinct clusters (e.g., black, gray, white). Pixels in the darkest cluster are labeled as black.
Here's some Python code implementing these strategies:
python
User
explain OpenCV’s adaptive thresholding
Assistant
OpenCV’s adaptive thresholding is a technique used to convert grayscale images into binary images. Unlike global thresholding, where a single threshold value is applied to the entire image, adaptive thresholding determines the threshold for each pixel based on the local neighborhood of that pixel. This is particularly useful for images where lighting conditions vary across the image, making it difficult to apply a single global threshold effectively.
Key Concepts of Adaptive Thresholding
Local Calculation: The threshold for each pixel is calculated using a small region around it. This allows the method to adapt to local variations in lighting and contrast.
Neighborhood Size: The size of the local region, often defined as a block size or neighborhood size, determines how many surrounding pixels influence the threshold calculation for a given pixel.
Adaptive Methods: OpenCV provides two main adaptive methods:
Mean of the Neighborhood: The threshold is the mean value of all the pixels in the neighborhood minus a constant C.
Gaussian Weighted Sum: The threshold is the weighted sum (Gaussian kernel) of all the pixel values in the neighborhood minus a constant C.
Constant C: A constant subtracted from the calculated mean or weighted sum to fine-tune the thresholding effect. It essentially provides a bias to adjust the thresholding sensitivity.
How to Use Adaptive Thresholding in OpenCV
Here's how you can perform adaptive thresholding using OpenCV in Python:
python
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Read a grayscale image
img = cv2.imread('manga_page.png', cv2.IMREAD_GRAYSCALE)
# Apply global thresholding for comparison
_, global_thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# Adaptive Mean Thresholding
adaptive_thresh_mean = cv2.adaptiveThreshold(
img,
255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
blockSize=11,
C=2
)
# Adaptive Gaussian Thresholding
adaptive_thresh_gaussian = cv2.adaptiveThreshold(
img,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
blockSize=11,
C=2
)
# Display the results
titles = ['Original Image', 'Global Thresholding', 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, global_thresh, adaptive_thresh_mean, adaptive_thresh_gaussian]
for i in range(4):
plt.subplot(2, 2, i+1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
User
explain k-means clustering in this context
Assistant
K-means clustering is a popular unsupervised machine learning algorithm typically used for partitioning data into K distinct clusters based on feature similarity. In the context of image processing, particularly for determining black pixels in grayscale manga, K-means can be used to group pixels into clusters of similar intensity levels. This allows for the segmentation of different tonal regions, which can help distinguish areas that represent "black", "gray", and "white" tones even if they don't correspond to precise pixel values.
How K-means Clustering is Applied in Grayscale Images
Convert Image Data:
The grayscale image is flattened into a one-dimensional array of pixel intensities. Each pixel intensity can be thought of as a point in a one-dimensional space.
For more complex segmentation, consider using two dimensions, such as intensity and spatial coordinates, but in this context, single-dimension based on intensity is more commonly applied.
Initialize Clusters:
You specify the number of clusters, K, that you want to identify in the data. In a grayscale image, you might choose K=3 to represent dark, medium, and light tones (or black, gray, and white regions).
Assign Pixels to Clusters:
The algorithm randomly assigns initial cluster centers and then iteratively updates them by assigning each pixel to the cluster with the nearest intensity.
It computes new centroids by averaging the intensities assigned to each cluster.
Iterate:
The process repeats until convergence, meaning the cluster assignments no longer change significantly, or a maximum number of iterations is reached.
Identify "Black" Cluster:
Once clustering is complete, the cluster with the lowest mean intensity is typically considered to represent the "black" pixels.
Create Binary Mask:
A binary mask can be generated where pixels belonging to the "black" cluster are set to True (or 1), and others to False (or 0).
Python Implementation with Scikit-learn
Here's a simple implementation of K-means clustering to identify black pixels.
python
User
implment k-means clustering to determin modal black in the following code: def adjust_grayscale_values(img: np.ndarray) -> tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
# Calculate modal white value in the range [250, 256)
hist_white, bins_white = np.histogram(img[img >= 250], bins=6, range=(250, 256))
modal_white = int(bins_white[np.argmax(hist_white)])
code
# Calculate modal black value in the range [0, 61)
hist_black, bins_black = np.histogram(img[img < 61], bins=61, range=(0, 61))
modal_black = int(bins_black[np.argmax(hist_black)])
# Convert image to float for processing
adjusted = img.astype(np.float64)
# Create a mask for extreme original values (0 and 255)
mask = (img == 0) | (img == 255)
# Exclude extreme values from the white adjustment
white_adjust_mask = ~mask
# Scale image if modal white is not at maximum intensity
if modal_white != 255:
adjusted[white_adjust_mask] *= 255.0 / modal_white
adjusted = np.clip(adjusted, 0, 255)
# After white value adjustment, identify new extreme values
new_extremes = (adjusted == 0) | (adjusted == 255)
# Combine masks to exclude all extreme values from black adjustment
total_extremes = mask | new_extremes
black_adjust_mask = ~total_extremes
# Adjust image based on modal black value
if modal_black:
adjusted[black_adjust_mask] = (
adjusted[black_adjust_mask] - modal_black
) * (255.0 / (255 - modal_black))
adjusted = np.clip(adjusted, 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted[black_adjust_mask] = (
np.power(adjusted[black_adjust_mask] / 255.0, gamma) * 255
)
# Round to nearest integer and then convert to uint8
adjusted = np.rint(adjusted).astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error_message(f"Error adjusting values for image: {e}")
return img, 0, 255
Assistant
To incorporate K-means clustering into your function for determining the modal black value, we'll focus on using K-means to identify tonal clusters and determine the darkest cluster's centroid as the effective "modal black." Here’s how you can modify your adjust_grayscale_values function to use K-means clustering for this purpose:
python
import numpy as np
from sklearn.cluster import KMeans
def adjust_grayscale_values(img: np.ndarray) -> tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
# Calculate modal white value in the range [250, 256)
hist_white, bins_white = np.histogram(img[img >= 250], bins=6, range=(250, 256))
modal_white = int(bins_white[np.argmax(hist_white)])
# Use K-means to determine modal black value
pixels = img.flatten().reshape(-1, 1)
kmeans = KMeans(n_clusters=3, random_state=0, n_init='auto')
kmeans.fit(pixels)
# Retrieve clustering results
centers = kmeans.cluster_centers_.flatten()
# Determine the darkest cluster center as modal black
modal_black = int(min(centers))
# Convert image to float for processing
adjusted = img.astype(np.float64)
# Create a mask for extreme original values (0 and 255)
mask = (img == 0) | (img == 255)
# Exclude extreme values from the white adjustment
white_adjust_mask = ~mask
# Scale image if modal white is not at maximum intensity
if modal_white != 255:
adjusted[white_adjust_mask] *= 255.0 / modal_white
adjusted = np.clip(adjusted, 0, 255)
# After white value adjustment, identify new extreme values
new_extremes = (adjusted == 0) | (adjusted == 255)
# Combine masks to exclude all extreme values from black adjustment
total_extremes = mask | new_extremes
black_adjust_mask = ~total_extremes
# Adjust image based on modal black value
if modal_black:
adjusted[black_adjust_mask] = (
adjusted[black_adjust_mask] - modal_black
) * (255.0 / (255 - modal_black))
adjusted = np.clip(adjusted, 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted[black_adjust_mask] = (
np.power(adjusted[black_adjust_mask] / 255.0, gamma) * 255
)
# Round to nearest integer and then convert to uint8
adjusted = np.rint(adjusted).astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error_message(f"Error adjusting values for image: {e}")
return img, 0, 255
# Example usage
# Make sure to import or implement the `log_error_message` function if it's not available
User
do the clustering with numpy
Assistant
Certainly! While using a library like scikit-learn makes K-means clustering straightforward, it can be done manually with numpy by following the algorithm's basic steps. Here's a simple implementation of K-means clustering to find the modal black in a grayscale image using only numpy:
python
User
Improve the speed of the clustering
Assistant
Manually implementing K-means clustering with numpy can be a great learning exercise, but it may not be as fast or efficient as using optimized libraries like scikit-learn. However, you can still make some improvements to the speed of the manual implementation:
Tips for Speeding Up K-means Clustering with Numpy
Vectorization: Ensure that operations are fully vectorized. This means leveraging numpy's ability to perform element-wise operations without explicit loops.
Efficient Initialization: Use more efficient initialization of cluster centers like k-means++ which helps in faster convergence.
Convergence Checking: Only perform convergence checks every few iterations to reduce overhead.
Parallel Processing: Although numpy is single-threaded, you could potentially leverage multiprocessing if operations can be split (note this won't be used in the code below).
Here’s an improved version with vectorization and efficient operations:
Description: Evaluate the distribution of tones and dynamically decide on a strategy for contrast adjustment.
Implementation:
python
def tone_based_adjustment(img: np.ndarray) -> np.ndarray:
hist, _ = np.histogram(img, bins=256, range=(0, 256))
if np.argmax(hist[128:]) > hist.sum() * 0.6:
# If mostly light tones, use a lighter adjustment
print("Light tones detected. Using advanced adjustment...")
adjusted = apply_clahe(img)
else:
# Fallback to original approach
adjusted = img
return adjusted
# Incorporate into your function
adjusted = tone_based_adjustment(adjusted)
These approaches can be mixed and matched depending on your specific needs and testing results. For practical usage, you may also want to add tunable parameters to let users choose which method suits their particular images best.
import cv2
import numpy as np
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
def determine_black_pixels(img: np.ndarray, method='manual', threshold=30) -> np.ndarray:
if method == 'manual':
# Manual threshold
black_pixels = img < threshold
elif method == 'adaptive':
# Adaptive thresholding
black_pixels = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2).astype(bool)
elif method == 'kmeans':
# K-means clustering
pixels = img.flatten().reshape(-1, 1)
kmeans = KMeans(n_clusters=3, random_state=0, n_init='auto')
kmeans.fit(pixels)
labels = kmeans.labels_
centers = kmeans.cluster_centers_.flatten()
# Find the darkest cluster
black_cluster = np.argmin(centers)
black_pixels = labels.reshape(img.shape) == black_cluster
return black_pixels
# Example usage:
img = cv2.imread('manga_image.png', cv2.IMREAD_GRAYSCALE)
# Analyze histogram
plt.hist(img.ravel(), bins=256, range=[0,256])
plt.title('Histogram')
plt.show()
# Determine black pixels using the chosen method
black_pixels_manual = determine_black_pixels(img, method='manual', threshold=30)
black_pixels_adaptive = determine_black_pixels(img, method='adaptive')
black_pixels_kmeans = determine_black_pixels(img, method='kmeans')
# Visualize the result
cv2.imshow("Manual Threshold Black Pixels", black_pixels_manual.astype(np.uint8) * 255)
cv2.imshow("Adaptive Threshold Black Pixels", black_pixels_adaptive.astype(np.uint8) * 255)
cv2.imshow("K-Means Black Pixels", black_pixels_kmeans.astype(np.uint8) * 255)
cv2.waitKey(0)
cv2.destroyAllWindows()
Tips:
Fine-tuning: Adjust the parameters (like threshold value, number of clusters) for the specific set of images you are working with.
Post-processing: You might want to employ morphological operations (e.g., erosion, dilation) to clean up the detected black regions by removing noise or filling small gaps.
Analysis Combination: Sometimes, a combination of methods (e.g., histogram study for initial threshold estimation followed by adaptive thresholding) can give the best results.
Parameters Explained
src: Source grayscale image.
maxValue: The maximum value assigned to the pixels that pass the thresholding condition. For binary images, this is often 255.
adaptiveMethod: Determines how the threshold for the pixel is calculated. Options are cv2.ADAPTIVE_THRESH_MEAN_C and cv2.ADAPTIVE_THRESH_GAUSSIAN_C.
thresholdType: The type of thresholding to apply. cv2.THRESH_BINARY is commonly used for adaptive thresholds.
blockSize: Size of the pixel neighborhood used to calculate the threshold. It must be an odd number (e.g., 3, 5, 7).
C: Constant subtracted from the mean or weighted mean. This value can be adjusted to fine-tune the results.
Advantages and Considerations
Advantages:
Performs well on images with non-uniform lighting.
Enhances details in variable lighting conditions.
Considerations:
The choice of block size and constant C significantly affects results; requires fine-tuning.
Computationally more intensive than global thresholding due to local calculations.
Adaptive thresholding is well-suited for tasks like document scanning, where lighting inconsistencies are common and maintaining detail is crucial.
import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# Load the grayscale image
img = cv2.imread('manga_page.png', cv2.IMREAD_GRAYSCALE)
# Flatten the image into a 1D array of pixel intensities
pixels = img.flatten().reshape(-1, 1)
# Apply K-means clustering
kmeans = KMeans(n_clusters=3, random_state=0, n_init='auto')
kmeans.fit(pixels)
# Retrieve clustering results
labels = kmeans.labels_
centers = kmeans.cluster_centers_
# Determine the cluster representing "black" pixels
black_cluster = np.argmin(centers)
# Create a binary mask for black pixels
black_pixels = (labels == black_cluster).reshape(img.shape)
# Display the original image and the binary mask
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title("Black Pixels")
plt.imshow(black_pixels, cmap='gray')
plt.axis('off')
plt.show()
Advantages and Considerations
Advantages:
Allows segmentation of images where direct thresholding isn't sufficient due to varying tones.
Adaptable to different images by adjusting the number of clusters.
Considerations:
The choice of K (number of clusters) is crucial; it depends on the specific image and the expected number of tonal regions.
K-means can be sensitive to the initial choice of cluster centers; using methods to initialize appropriately (like k-means++) can mitigate this.
Computationally more intensive than simple thresholding, but it offers a powerful approach for complex images with subtle tonal differences.
By classifying pixel intensities into clusters, K-means clustering helps to distinguish meaningful patterns and regions in the image that correspond to black or near-black tones in manga and similar grayscale imagery.
Key Changes in the Code:
K-means Clustering:
We applied K-means to the flattened pixel values with n_clusters=3, assuming three primary tonal regions: black, gray, and white.
Modal Black Determination:
We determined the "modal black" as the minimum value among the cluster centers returned by K-means, as this represents the darkest cluster.
Considerations:
Cluster Count: The choice of n_clusters=3 is arbitrary but reasonable for distinguishing black, gray, and white areas in typical grayscale images. You may need to adjust this depending on the image characteristics.
Initialization: The random_state ensures reproducibility, while n_init='auto' ensures robust initializations.
Performance: K-means clustering introduces more computational overhead compared to simple histogram analysis, but it provides a more robust approach to identifying clusters when precise thresholds are impractical due to variations in image tones.
import numpy as np
def kmeans_manual(data, k, max_iters=100, tol=1e-4):
# Randomly initialize k cluster centers
min_val, max_val = np.min(data), np.max(data)
centers = np.random.uniform(min_val, max_val, k)
for _ in range(max_iters):
# Assign clusters based on closest center
distances = np.abs(data - centers[:, np.newaxis])
labels = np.argmin(distances, axis=0)
# Calculate new centers
new_centers = np.array([data[labels == i].mean() for i in range(k)])
# Check for convergence
if np.all(np.abs(new_centers - centers) < tol):
break
centers = new_centers
return centers, labels
def adjust_grayscale_values(img: np.ndarray) -> tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
# Calculate modal white value in the range [250, 256)
hist_white, bins_white = np.histogram(img[img >= 250], bins=6, range=(250, 256))
modal_white = int(bins_white[np.argmax(hist_white)])
# Use numpy to perform K-means clustering for modal black
pixels = img.flatten()
# Perform K-means clustering to find modal black
centers, labels = kmeans_manual(pixels, k=3)
modal_black = int(min(centers))
# Convert image to float for processing
adjusted = img.astype(np.float64)
# Create a mask for extreme original values (0 and 255)
mask = (img == 0) | (img == 255)
# Exclude extreme values from the white adjustment
white_adjust_mask = ~mask
# Scale image if modal white is not at maximum intensity
if modal_white != 255:
adjusted[white_adjust_mask] *= 255.0 / modal_white
adjusted = np.clip(adjusted, 0, 255)
# After white value adjustment, identify new extreme values
new_extremes = (adjusted == 0) | (adjusted == 255)
# Combine masks to exclude all extreme values from black adjustment
total_extremes = mask | new_extremes
black_adjust_mask = ~total_extremes
# Adjust image based on modal black value
if modal_black:
adjusted[black_adjust_mask] = (
adjusted[black_adjust_mask] - modal_black
) * (255.0 / (255 - modal_black))
adjusted = np.clip(adjusted, 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted[black_adjust_mask] = (
np.power(adjusted[black_adjust_mask] / 255.0, gamma) * 255
)
# Round to nearest integer and then convert to uint8
adjusted = np.rint(adjusted).astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error_message(f"Error adjusting values for image: {e}")
return img, 0, 255
# Example usage
# Make sure to import or implement the `log_error_message` function if it's not available
How This Works
Initialization: We randomly initialize k cluster centers within the range of pixel values. Here, k=3 assumes we are distinguishing three tone regions (dark, medium, light).
Assignment: Each pixel is assigned to the nearest cluster center by computing the absolute distance.
Update: The centers are updated as the mean of the pixels in each cluster.
Convergence Check: The iteration stops when the centers stabilize within a small tolerance.
Cluster Selection: The cluster with the minimum center value is considered to represent "black."
This uses the core principles of K-means clustering but is implemented using basic numpy operations. This may result in relatively simple and less optimized code compared to using specialized libraries like scikit-learn.
import numpy as np
def kmeans_manual(data, k, max_iters=100, tol=1e-4):
# Randomly initialize k cluster centers using k-means++
def initialize_centers(data, k):
centers = [data[np.random.choice(range(len(data)))]]
for _ in range(1, k):
dists = np.array([min(np.linalg.norm(x - c)**2 for c in centers) for x in data])
probs = dists / dists.sum()
cumulative_probs = np.cumsum(probs)
r = np.random.rand()
i = np.where(cumulative_probs >= r)[0][0]
centers.append(data[i])
return np.array(centers)
centers = initialize_centers(data, k)
for _ in range(max_iters):
# Assign clusters using vectorized operations
distances = np.linalg.norm(data - centers[:, np.newaxis], axis=2)
labels = np.argmin(distances, axis=0)
# Recalculate centers vectorized
new_centers = np.array([data[labels == i].mean() for i in range(k) if len(data[labels == i]) > 0])
# Break if converged
if np.all(np.abs(new_centers - centers) < tol):
break
centers = new_centers
return centers, labels
def adjust_grayscale_values(img: np.ndarray) -> tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
# Calculate modal white value in the range [250, 256)
hist_white, bins_white = np.histogram(img[img >= 250], bins=6, range=(250, 256))
modal_white = int(bins_white[np.argmax(hist_white)])
# Use numpy to perform K-means clustering for modal black
pixels = img.flatten().reshape(-1, 1)
# Perform K-means clustering to find modal black
centers, labels = kmeans_manual(pixels.astype(float), k=3)
modal_black = int(min(centers))
# Convert image to float for processing
adjusted = img.astype(np.float64)
# Create a mask for extreme original values (0 and 255)
mask = (img == 0) | (img == 255)
# Exclude extreme values from the white adjustment
white_adjust_mask = ~mask
# Scale image if modal white is not at maximum intensity
if modal_white != 255:
adjusted[white_adjust_mask] *= 255.0 / modal_white
adjusted = np.clip(adjusted, 0, 255)
# After white value adjustment, identify new extreme values
new_extremes = (adjusted == 0) | (adjusted == 255)
# Combine masks to exclude all extreme values from black adjustment
total_extremes = mask | new_extremes
black_adjust_mask = ~total_extremes
# Adjust image based on modal black value
if modal_black:
adjusted[black_adjust_mask] = (
adjusted[black_adjust_mask] - modal_black
) * (255.0 / (255 - modal_black))
adjusted = np.clip(adjusted, 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted[black_adjust_mask] = (
np.power(adjusted[black_adjust_mask] / 255.0, gamma) * 255
)
# Round to nearest integer and then convert to uint8
adjusted = np.rint(adjusted).astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error_message(f"Error adjusting values for image: {e}")
return img, 0, 255
# Example usage
# Make sure to import or implement the `log_error_message` function if it's not available
Key Improvements
K-means++ Initialization: Using the k-means++ method for initialization helps in speeding up convergence by starting with centers that are well-spread.
Vectorization: The code uses numpy's vectorized operations to compute distances and assign labels, avoiding loops where possible.
Convergence Check Optimization: Centers are recalculated based on the mean of existing labels, with convergence checks done at a single point to speed up the process.
These modifications bring the manual implementation of K-means closer to the efficiency of optimized libraries. Nevertheless, for best performance in real-world applications, using a well-tuned library like scikit-learn remains the gold standard due to its better optimization and parallel processing capabilities.