import json
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from pdf2image import convert_from_path
import cv2
from sklearn.cluster import AgglomerativeClustering
import networkx as nx
import time
class UnionFind:
def init(self, size):
self.parent = list(range(size))
code
def find(self, u):
while self.parent[u] != u:
self.parent[u] = self.parent[self.parent[u]] # Path compression
u = self.parent[u]
return u
def union(self, u, v):
pu = self.find(u)
pv = self.find(v)
if pu != pv:
self.parent[pu] = pv # Merge the sets
def reconstruct_text(lines):
"""
Reconstruct text from grouped lines.
Each line is a list of dictionaries.
"""
reconstructed_lines = []
for line in lines:
# Sort line by x1
sorted_line = sorted(line, key=lambda elem: elem['x1'])
# Join text with spaces
line_text = ' '.join(elem['text'] for elem in sorted_line)
reconstructed_lines.append(line_text)
print('\n'.join(reconstructed_lines))
code
return '\n'.join(reconstructed_lines)
def visualize_with_text_and_image(image, reconstructed_text, lines, method='clustering'):
"""
Create a side-by-side visualization of the reconstructed text and the image with bounding boxes.
code
Parameters:
- image: The original image as a NumPy array.
- reconstructed_text: The reconstructed text string.
- lines: List of lines, each line is a list of dictionaries.
- method: The grouping method used (for title purposes).
"""
# Create a copy of the image to draw colored bounding boxes
img_copy = image.copy()
# Define colors for different lines using a colormap
colors = plt.colormaps['hsv'](np.linspace(0, 1, len(lines) + 1))
for idx, line in enumerate(lines):
color = tuple([int(255 * c) for c in colors[idx][:3]]) # Convert to 0-255 scale
for elem in line:
x1, y1, x2, y2 = elem['x1'], elem['y1'], elem['x2'], elem['y2']
cv2.rectangle(img_copy, (x1, y1), (x2, y2), color, 2)
# Convert image from BGR to RGB for matplotlib
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
# Create a matplotlib figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(25, 15))
axes[0].axis('off')
axes[0].text(0, 1, reconstructed_text, fontsize=12, va='top', wrap=True)
axes[0].set_title(f'Reconstructed Text using {method.capitalize()} Method', fontsize=16)
# Right subplot: Image with Bounding Boxes
axes[1].imshow(img_rgb)
axes[1].axis('off')
axes[1].set_title('OCR Bounding Boxes', fontsize=16)
plt.tight_layout()
plt.show()
Assistant
User
AttributeError: module 'matplotlib.pyplot' has no attribute 'colors'
Assistant
User
Assistant
User
I want to use my plt.colormaps
Assistant
def load_ocr_data(json_filename):
"""
Load OCR data from a JSON file into a pandas DataFrame.
"""
with open(json_filename, 'r', encoding='utf-8') as json_file:
bbox = json.load(json_file)
df = pd.DataFrame(bbox)
return df
def preprocess_df(df):
"""
Preprocess the DataFrame by ensuring required columns are present and correctly typed.
"""
required_columns = ['x1', 'y1', 'x2', 'y2', 'height', 'width', 'text', 'type_of_text', 'new_line', 'region']
for col in required_columns:
if col not in df.columns:
raise ValueError(f"Missing required column: {col}")
# Convert coordinates and size columns to integers
df[['x1', 'y1', 'x2', 'y2', 'height', 'width']] = df[['x1', 'y1', 'x2', 'y2', 'height', 'width']].astype(int)
return df
can you apply on each row in reconstructed_text a color that matches the row in right subplot with bounding boxes?
To achieve the alignment between the reconstructed text colors and the bounding box colors in the side-by-side visualization, you can modify the visualize_with_text_and_image function to apply the same color to each line of text as the corresponding bounding boxes. Here's a step-by-step guide to implementing this:
Keep track of the colors used for each line by storing them in a list or similar structure.
Use this list to apply the same color to the text when displaying it on the left subplot.
Here's how you can modify the visualize_with_text_and_image function:
python
def visualize_with_text_and_image(image, reconstructed_text, lines, method='clustering'):
"""
Create a side-by-side visualization of the reconstructed text and the image with bounding boxes.
Parameters:
- image: The original image as a NumPy array.
- reconstructed_text: List of strings, where each string is a reconstructed line of text.
- lines: List of lines, each line is a list of dictionaries.
- method: The grouping method used (for title purposes).
"""
# Create a copy of the image to draw colored bounding boxes
img_copy = image.copy()
# Define colors for different lines using a colormap
colors = plt.colormaps['hsv'](np.linspace(0, 1, len(lines) + 1))
for idx, line in enumerate(lines):
color = tuple([int(255 * c) for c in colors[idx][:3]]) # Convert to 0-255 scale
for elem in line:
x1, y1, x2, y2 = elem['x1'], elem['y1'], elem['x2'], elem['y2']
cv2.rectangle(img_copy, (x1, y1), (x2, y2), color, 2)
# Convert image from BGR to RGB for matplotlib
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
# Create a matplotlib figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(25, 15))
axes[0].axis('off')
# Initialize cursor position for text annotation
y_cursor = 1.0
# Loop over reconstructed text and colors to display them
for idx, (line_text, color) in enumerate(zip(reconstructed_text, colors)):
# Convert color to HEX for matplotlib
hex_color = matplotlib.colors.rgb2hex(color[:3])
# Display each line with corresponding color
axes[0].text(0, y_cursor, line_text, fontsize=12, va='top', color=hex_color)
# Adjust y_cursor for next line
y_cursor -= 0.05 # Adjust this value depending on the spacing you want
axes[0].set_title(f'Reconstructed Text using {method.capitalize()} Method', fontsize=16)
# Right subplot: Image with Bounding Boxes
axes[1].imshow(img_rgb)
axes[1].axis('off')
axes[1].set_title('OCR Bounding Boxes', fontsize=16)
plt.tight_layout()
plt.show()
Additional Notes:
Make sure to update the call to reconstruct_text so that it returns a list of reconstructed lines instead of a single string. This way, each line can be individually colored.
You may need to adjust the positioning logic for text (y_cursor decrement) to suit your layout needs. Adjust the value by experimenting with the spacing between lines.
The hex_color is used to match colors in matplotlib. Adjust your color conversions accordingly if using a different module for colors.
The error you're encountering arises from the incorrect attribute access for color conversion in Matplotlib. matplotlib.pyplot module doesn't have a colors attribute. Instead, use matplotlib.colors for color conversion tasks.
Here's the corrected code snippet:
python
import matplotlib
def visualize_with_text_and_image(image, reconstructed_text, lines, method='clustering'):
"""
Create a side-by-side visualization of the reconstructed text and the image with bounding boxes.
Parameters:
- image: The original image as a NumPy array.
- reconstructed_text: List of strings, where each string is a reconstructed line of text.
- lines: List of lines, each line is a list of dictionaries.
- method: The grouping method used (for title purposes).
"""
# Create a copy of the image to draw colored bounding boxes
img_copy = image.copy()
# Define colors for different lines using a colormap
colors = plt.cm.hsv(np.linspace(0, 1, len(lines) + 1))
for idx, line in enumerate(lines):
color = tuple([int(255 * c) for c in colors[idx][:3]]) # Convert to 0-255 scale
for elem in line:
x1, y1, x2, y2 = elem['x1'], elem['y1'], elem['x2'], elem['y2']
cv2.rectangle(img_copy, (x1, y1), (x2, y2), color, 2)
# Convert image from BGR to RGB for matplotlib
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
# Create a matplotlib figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(25, 15))
axes[0].axis('off')
# Initialize cursor position for text annotation
y_cursor = 1.0
# Loop over reconstructed text and colors to display them
for idx, (line_text, color) in enumerate(zip(reconstructed_text, colors)):
# Convert color to HEX for matplotlib
hex_color = matplotlib.colors.rgb2hex(color[:3])
# Display each line with corresponding color
axes[0].text(0, y_cursor, line_text, fontsize=12, va='top', wrap=True, color=hex_color)
# Adjust y_cursor for next line
y_cursor -= 0.05 # Adjust this value depending on the spacing you want
axes[0].set_title(f'Reconstructed Text using {method.capitalize()} Method', fontsize=16)
# Right subplot: Image with Bounding Boxes
axes[1].imshow(img_rgb)
axes[1].axis('off')
axes[1].set_title('OCR Bounding Boxes', fontsize=16)
plt.tight_layout()
plt.show()
Key Changes:
Imported matplotlib.colors explicitly.
Corrected the color conversion to use matplotlib.colors.rgb2hex to convert RGB values to hex code for text color rendering.
Remember to pass reconstructed_text as a list of text lines for this visualization function to work correctly. Let me know if you have more questions!
ValueError Traceback (most recent call last)
Cell In[139], line 137
135 for filename in os.listdir("Sortowanie"):
136 if filename.endswith(".pdf"):
--> 137 main(filename[:-4])
Cell In[138], line 86, in visualize_with_text_and_image(image, reconstructed_text, lines, method)
84 line_height = 0.01 # Adjust to control spacing between lines
85 for line_text, color in text_lines:
---> 86 axes[0].text(0, y_position, line_text, fontsize=12, va='top', color=color)
87 y_position -= line_height # Move down for the next line
88 axes[0].set_xlim(0, 1)
File /opt/conda/lib/python3.10/site-packages/matplotlib/axes/_axes.py:689, in Axes.text(self, x, y, s, fontdict, **kwargs)
628 """
629 Add text to the Axes.
630
(...)
679 >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
680 """
681 effective_kwargs = {
682 'verticalalignment': 'baseline',
683 'horizontalalignment': 'left',
(...)
687 **kwargs,
688 }
--> 689 t = mtext.Text(x, y, text=s, **effective_kwargs)
690 t.set_clip_path(self.patch)
691 self._add_text(t)
File /opt/conda/lib/python3.10/site-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only..wrapper(*args, **kwargs)
448 if len(args) > name_idx:
449 warn_deprecated(
450 since, message="Passing the %(name)s %(obj_type)s "
451 "positionally is deprecated since Matplotlib %(since)s; the "
452 "parameter will become keyword-only %(removal)s.",
453 name=name, obj_type=f"parameter of {func.name}()")
--> 454 return func(*args, **kwargs)
File /opt/conda/lib/python3.10/site-packages/matplotlib/text.py:202, in Text._reset_visual_defaults(self, text, color, fontproperties, usetex, parse_math, wrap, verticalalignment, horizontalalignment, multialignment, rotation, transform_rotates_text, linespacing, rotation_mode)
185 def _reset_visual_defaults(
186 self,
187 text='',
(...)
199 rotation_mode=None,
200 ):
201 self.set_text(text)
--> 202 self.set_color(
203 color if color is not None else mpl.rcParams["text.color"])
204 self.set_fontproperties(fontproperties)
205 self.set_usetex(usetex)
File /opt/conda/lib/python3.10/site-packages/matplotlib/text.py:996, in Text.set_color(self, color)
993 # "auto" is only supported by axisartist, but we can just let it error
994 # out at draw time for simplicity.
995 if not cbook._str_equal(color, "auto"):
--> 996 mpl.colors._check_color_like(color=color)
997 self._color = color
998 self.stale = True
File /opt/conda/lib/python3.10/site-packages/matplotlib/colors.py:243, in _check_color_like(**kwargs)
241 for k, v in kwargs.items():
242 if not is_color_like(v):
--> 243 raise ValueError(f"{v!r} is not a valid value for {k}")
ValueError: (255, 0, 0) is not a valid value for color
import json
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from pdf2image import convert_from_path
import cv2
from sklearn.cluster import AgglomerativeClustering
import networkx as nx
import time
class UnionFind:
def init(self, size):
self.parent = list(range(size))
code
def find(self, u):
while self.parent[u] != u:
self.parent[u] = self.parent[self.parent[u]] # Path compression
u = self.parent[u]
return u
def union(self, u, v):
pu = self.find(u)
pv = self.find(v)
if pu != pv:
self.parent[pu] = pv # Merge the sets
def reconstruct_text(lines):
"""
Reconstruct text from grouped lines.
Each line is a list of dictionaries.
"""
reconstructed_lines = []
for line in lines:
# Sort line by x1
sorted_line = sorted(line, key=lambda elem: elem['x1'])
# Join text with spaces
line_text = ' '.join(elem['text'] for elem in sorted_line)
reconstructed_lines.append(line_text)
print('\n'.join(reconstructed_lines))
code
return '\n'.join(reconstructed_lines)
def visualize_with_text_and_image(image, reconstructed_text, lines, method='clustering'):
"""
Create a side-by-side visualization of the reconstructed text and the image with bounding boxes.
code
Parameters:
- image: The original image as a NumPy array.
- reconstructed_text: The reconstructed text string.
- lines: List of lines, each line is a list of dictionaries.
- method: The grouping method used (for title purposes).
"""
# Create a copy of the image to draw colored bounding boxes
img_copy = image.copy()
# Define colors for different lines using a colormap
colors = plt.colormaps['hsv'](np.linspace(0, 1, len(lines) + 1))
# Prepare the left subplot text lines
# We'll render each line with its color, in order
text_lines = []
for idx, line in enumerate(lines):
color = tuple([int(255 * c) for c in colors[idx][:3]]) # Convert to 0-255 scale
# Sort line by x1
sorted_line = sorted(line, key=lambda elem: elem['x1'])
# Join texts
line_text = ' '.join(elem['text'] for elem in sorted_line)
text_lines.append((line_text, color))
# Draw bounding boxes with color
for elem in line:
x1, y1, x2, y2 = elem['x1'], elem['y1'], elem['x2'], elem['y2']
cv2.rectangle(img_copy, (x1, y1), (x2, y2), tuple(int(255 * c) for c in color), 2)
# Convert image from BGR to RGB for matplotlib
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
# Create a matplotlib figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(25, 15))
# Left subplot: Reconstructed Text with colors
axes[0].axis('off')
y_position = 1.0 # Start from top
line_height = 0.01 # Adjust to control spacing between lines
for line_text, color in text_lines:
axes[0].text(0, y_position, line_text, fontsize=12, va='top', color=color)
y_position -= line_height # Move down for the next line
axes[0].set_xlim(0, 1)
axes[0].set_ylim(0, 1)
axes[0].set_title(f'Reconstructed Text using {method.capitalize()} Method', fontsize=16)
# Right subplot: Image with Bounding Boxes
axes[1].imshow(img_rgb)
axes[1].axis('off')
axes[1].set_title('OCR Bounding Boxes', fontsize=16)
plt.tight_layout()
plt.show()
print(f"Displayed visualization for {method.capitalize()} grouping.")
def load_ocr_data(json_filename):
"""
Load OCR data from a JSON file into a pandas DataFrame.
"""
with open(json_filename, 'r', encoding='utf-8') as json_file:
bbox = json.load(json_file)
df = pd.DataFrame(bbox)
return df
def preprocess_df(df):
"""
Preprocess the DataFrame by ensuring required columns are present and correctly typed.
"""
required_columns = ['x1', 'y1', 'x2', 'y2', 'height', 'width', 'text', 'type_of_text', 'new_line', 'region']
for col in required_columns:
if col not in df.columns:
raise ValueError(f"Missing required column: {col}")
# Convert coordinates and size columns to integers
df[['x1', 'y1', 'x2', 'y2', 'height', 'width']] = df[['x1', 'y1', 'x2', 'y2', 'height', 'width']].astype(int)
return df
The error you're encountering is because the color passed to axes[0].text is in the form of a tuple with values scaled to 255, which is not valid for the color parameter in Matplotlib. Matplotlib expects colors to be in the form of either a string, a hex string, or a tuple with each component a float between 0 and 1.
Let's adjust the visualization function to fix this issue by converting the color tuples to the expected format:
python
import matplotlib
def visualize_with_text_and_image(image, reconstructed_text, lines, method='clustering'):
"""
Create a side-by-side visualization of the reconstructed text and the image with bounding boxes.
Parameters:
- image: The original image as a NumPy array.
- reconstructed_text: The reconstructed text string.
- lines: List of lines, each line is a list of dictionaries.
- method: The grouping method used (for title purposes).
"""
# Create a copy of the image to draw colored bounding boxes
img_copy = image.copy()
# Define colors for different lines using a colormap
colors = plt.cm.hsv(np.linspace(0, 1, len(lines) + 1))
# Prepare the left subplot text lines
text_lines = []
for idx, line in enumerate(lines):
# Extract the color for the current line as a tuple of floats (for Matplotlib)
color_rgb = colors[idx][:3]
# Convert the color to integers for OpenCV
color_bgr_cv2 = tuple(int(255 * c) for c in color_rgb)
# Sort line by x1
sorted_line = sorted(line, key=lambda elem: elem['x1'])
# Join texts
line_text = ' '.join(elem['text'] for elem in sorted_line)
text_lines.append((line_text, color_rgb))
# Draw bounding boxes with color
for elem in line:
x1, y1, x2, y2 = elem['x1'], elem['y1'], elem['x2'], elem['y2']
cv2.rectangle(img_copy, (x1, y1), (x2, y2), color_bgr_cv2, 2)
# Convert image from BGR to RGB for Matplotlib
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
# Create a Matplotlib figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(25, 15))
# Left subplot: Reconstructed Text with colors
axes[0].axis('off')
y_position = 1.0 # Start from top
line_height = 0.05 # Adjust to control spacing between lines
for line_text, color_rgb in text_lines:
hex_color = matplotlib.colors.rgb2hex(color_rgb)
axes[0].text(0, y_position, line_text, fontsize=12, va='top', color=hex_color, wrap=True)
y_position -= line_height # Move down for the next line
axes[0].set_xlim(0, 1)
axes[0].set_ylim(0, 1)
axes[0].set_title(f'Reconstructed Text using {method.capitalize()} Method', fontsize=16)
# Right subplot: Image with Bounding Boxes
axes[1].imshow(img_rgb)
axes[1].axis('off')
axes[1].set_title('OCR Bounding Boxes', fontsize=16)
plt.tight_layout()
plt.show()
print(f"Displayed visualization for {method.capitalize()} grouping.")
Key Changes:
Color Conversion: Use matplotlib.colors.rgb2hex to convert RGB tuples to HEX color codes for the text rendering in Matplotlib.
Color Representation for OpenCV: Convert colors to BGR format with integer values scaled between 0 and 255 when drawing rectangles with OpenCV.
Check Line Height: The line_height is adjusted to 0.05 for visible separation of text lines. Adjust further if needed for your specific visual clarity.
This setup should resolve the error and provide clear color-coded text that matches with the bounding boxes in the image.
If you wish to directly use the colormaps available in Matplotlib through plt.colormaps, you can adapt the code to fit the color format requirements of both Matplotlib for plotting text and OpenCV for drawing rectangles.
Here's the revised function using plt.colormaps to generate colors for both the text and bounding boxes:
python
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def visualize_with_text_and_image(image, lines, method='clustering'):
"""
Create a side-by-side visualization of the reconstructed text and the image with bounding boxes.
Parameters:
- image: The original image as a NumPy array.
- lines: List of lines, each line is a list of dictionaries.
- method: The grouping method used (for title purposes).
"""
# Create a copy of the image to draw colored bounding boxes
img_copy = image.copy()
# Define colors for different lines using a colormap
colormap = plt.get_cmap('hsv')
colors = [colormap(i) for i in np.linspace(0, 1, len(lines) + 1)]
# Prepare the left subplot text lines
text_lines = []
for idx, line in enumerate(lines):
color_rgb = colors[idx][:3] # Use the first three values as RGB
color_bgr_cv2 = tuple(int(255 * c) for c in reversed(color_rgb)) # Convert to BGR for OpenCV
# Sort line by x1
sorted_line = sorted(line, key=lambda elem: elem['x1'])
# Join texts
line_text = ' '.join(elem['text'] for elem in sorted_line)
text_lines.append((line_text, color_rgb))
# Draw bounding boxes with color
for elem in line:
x1, y1, x2, y2 = elem['x1'], elem['y1'], elem['x2'], elem['y2']
cv2.rectangle(img_copy, (x1, y1), (x2, y2), color_bgr_cv2, 2)
# Convert image from BGR to RGB for Matplotlib
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
# Create a Matplotlib figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(25, 15))
# Left subplot: Reconstructed Text with colors
axes[0].axis('off')
y_position = 1.0 # Start from top
line_height = 0.05 # Adjust to control spacing between lines
for line_text, color_rgb in text_lines:
hex_color = mcolors.rgb2hex(color_rgb)
axes[0].text(0, y_position, line_text, fontsize=12, va='top', color=hex_color, wrap=True)
y_position -= line_height # Move down for the next line
axes[0].set_xlim(0, 1)
axes[0].set_ylim(0, 1)
axes[0].set_title(f'Reconstructed Text using {method.capitalize()} Method', fontsize=16)
# Right subplot: Image with Bounding Boxes
axes[1].imshow(img_rgb)
axes[1].axis('off')
axes[1].set_title('OCR Bounding Boxes', fontsize=16)
plt.tight_layout()
plt.show()
print(f"Displayed visualization for {method.capitalize()} grouping.")
Key Points:
Using plt.get_cmap: This function retrieves a colormap that you can then sample colors from using a linear space across the range of the colormap.
Color Conversion: For OpenCV, you must reverse the RGB order to BGR and scale the values to 255, whereas for Matplotlib text, use the RGB to HEX transformation.
np.linspace for Colors: This provides an even distribution of colors across the available range in the colormap.
This approach ensures both your text and bounding boxes are color-coordinated according to your chosen colormap from plt.colormaps.