Business Context
In our use case, users enter a URL to generate a matching website. That means we need to screenshot the original site, split the screenshot into blocks, and send each block to an AI to generate code.
The Problem
The current computer vision (CV) approach uses pixel detection and an adaptive-width algorithm to segment the page. Its results, however, differ significantly from how people actually perceive the page.
To make this clearer, here’s a simple example:

745b70f0-a578-4e3e-a0e5-4fe7580ed84f_comparison.png
This approach has several major problems:
- Text content gets cut in inappropriate places.
- Images are broken apart as a whole.
- Content is divided into multiple parts in illogical ways.
- The segmentation results are far from human visual perception.
Algorithm Considerations
To solve these problems, we need to explore and propose better algorithm strategies. Here are a few possible approaches:
Segment AI
Use Segment AI to semantically guide segmentation of the long screenshot. This approach can help understand the image content and improve segmentation accuracy. We could consider Meta AI's Segment Anything tool and evaluate whether it suits our needs. Link: https://segment-anything.com/
OmniParser

image.png
OmniParser is mainly used to label GUI elements. Although it is efficient in many scenarios, it is relatively impractical for our current task.
HTML Layout Annotation + CV Segmentation
This approach is more engineering-friendly. The problem with our existing algorithm is that webpage screenshots have a lot of pixel noise, which makes a pure CV approach struggle. So we can improve it by color-coding the layout of the original HTML structure. HTML is essentially a DOM tree from root to leaf. We can traverse elements top-down along the tree, and if an element's size matches the viewport, color that section. Then apply a CV method to segment the image. The result of this algorithm is shown below and basically meets our needs:

image.png
Algorithm Demo
import cv2
import numpy as np
from PIL import Image
import pytesseract
# Configure the Tesseract path (only needed on Windows)
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def detect_red_borders(image):
"""
Detect red dashed borders in the image and return the border contours.
"""
# Convert to the HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Set the red HSV ranges
lower_red1 = np.array([0, 100, 100])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([160, 100, 100])
upper_red2 = np.array([180, 255, 255])
# Create a red mask
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
mask = cv2.bitwise_or(mask1, mask2)
# Use a larger kernel for morphological operations to connect the dashed lines into complete borders
kernel = np.ones((5,5), np.uint8) # Adjust the kernel size as needed
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2) # Adjust the number of iterations
# Use Canny edge detection to help detect the dashed lines
edges = cv2.Canny(mask, 50, 150)
# Find contours
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Filter and store the border contours
red_borders = []
min_area = 5000 # Adjust the minimum area threshold based on your situation
for cnt in contours:
area = cv2.contourArea(cnt)
if area > min_area:
x, y, w, h = cv2.boundingRect(cnt)
red_borders.append((x, y, w, h))
# Draw the detected region on the original image
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Save intermediate results for debugging
cv2.imwrite('debug_mask.png', mask)
cv2.imwrite('debug_edges.png', edges)
cv2.imwrite('debug_contours.png', image)
return red_borders
def detect_block_labels(image, red_borders):
"""
Detect the locations of "Block" labels inside the red border regions.
Return the region coordinates for each border.
"""
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
# OCR
pil_img = Image.fromarray(thresh)
data = pytesseract.image_to_data(pil_img, config='--psm 6', output_type=pytesseract.Output.DICT)
n_boxes = len(data['level'])
block_labels = []
for i in range(n_boxes):
text = data['text'][i].strip()
if 'block' in text.lower():
(x, y, w, h) = (data['left'][i], data['top'][i], data['width'][i], data['height'][i])
block_labels.append((x, y, w, h))
return block_labels
def extract_blocks(image, red_borders):
"""
Extract the corresponding blocks from the image based on the detected red borders.
Return a list containing the block images.
"""
blocks = []
for idx, (x, y, w, h) in enumerate(red_borders):
# Extract the block region
block = image[y:y+h, x:x+w]
blocks.append(block)
# Optional: save each block to a file
# cv2.imwrite(f'block_{idx+1}.png', block)
return blocks
def main():
# Load the long screenshot
image_path = 'img_1.png' # Replace with your screenshot path
image = cv2.imread(image_path)
if image is None:
print(f"Could not load image: {image_path}")
return
else:
print(f"Loaded image successfully: {image_path}, size: {image.shape}")
# Use the modified detection function
red_borders = detect_red_borders(image)
print(f"Detected {len(red_borders)} red borders.")
if len(red_borders) == 0:
print("No red borders were detected. Check the border color range and make sure the screenshot is correct.")
# Continue running to inspect the debug images
# View the generated debug images:
# - debug_mask.png: red mask
# - debug_edges.png: Canny edge map
# - debug_contours.png: detected contours drawn on the original image
# Visualize the detected red borders
cv2.imshow('Detected Red Borders', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Optional: detect "Block" labels
blocks = detect_block_labels(image, red_borders)
print("Detected labels:", blocks)
# Extract blocks
extracted_blocks = extract_blocks(image, red_borders)
print(f"Extracted {len(extracted_blocks)} blocks.")
# Save the extracted blocks
for idx, block in enumerate(extracted_blocks):
block_path = f'block_{idx+1}.png'
cv2.imwrite(block_path, block)
print(f"Saved block to: {block_path}")
if __name__ == "__main__":
main()
Reflections
When facing complex real-world business scenarios, if you run into a problem that is hard to solve, it can help to start with a simple algorithm and gradually address each obstacle it encounters. This approach gives us a fresh perspective for finding more effective solutions.