# OpenCv contours only around columns in Red Boxes

**URL:** <https://forum.opencv.org/t/opencv-contours-only-around-columns-in-red-boxes/9242>\
**Category:** Python\
**Tags:** contours\
**Created:** [June 20, 2022, 11:13am UTC](https://forum.opencv.org/t/opencv-contours-only-around-columns-in-red-boxes/9242 "2022-06-20T11:13:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hyder](https://avatars.discourse-cdn.com/v4/letter/h/a183cd/32.png) [@Hyder](https://forum.opencv.org/u/Hyder)\
**Post date:** [June 20, 2022, 11:13am UTC](https://forum.opencv.org/t/opencv-contours-only-around-columns-in-red-boxes/9242/1 "2022-06-20T11:13:18Z")

</div>

I am trying to make contours only in red rectangle areas in the original image. So that OpenCV will send only specific text for tesseract OCR. My current code is making contours over the whole tables. I am not much aware of OpenCV. How I can add red Square detection part in my code?

**Code:**

​ import cv2port cv2

import matplotlib.pyplot as plt

def mark\_region(image\_path):

image = cv2.imread(image\_path)

_#CONFUSION IN THIS PART_

lower = np.array([0,175,20], np.uint8)

upper = np.array([10, 255,255], np.uint8)

mask = cv2.inRange(image, lower, upper)

_#CONFUSION IN THIS PART_

# define threshold of regions to ignore

THRESHOLD\_REGION\_IGNORE = 40

gray = cv2.cvtColor(image, cv2.COLOR\_BGR2GRAY)

blur = cv2.GaussianBlur(gray, (3,3), 0)

thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE\_THRESH\_GAUSSIAN\_C, cv2.THRESH\_BINARY\_INV,11,30)

# Dilate to combine adjacent text contours

kernel = cv2.getStructuringElement(cv2.MORPH\_RECT, (3,3))

dilate = cv2.dilate(thresh, kernel, iterations=4)

# Find contours, highlight text areas, and extract ROIs

cnts = cv2.findContours(dilate, cv2.RETR\_EXTERNAL, cv2.CHAIN\_APPROX\_SIMPLE)

cnts = cnts[0] if len(cnts) == 2 else cnts[1]

line\_items\_coordinates =

for c in cnts:

area = cv2.contourArea(c)

x, y, w, h = cv2.boundingRect(c)

if w \< THRESHOLD\_REGION\_IGNORE or h \< THRESHOLD\_REGION\_IGNORE:

continue

image = cv2.rectangle(image, (x,y), (x+w, y+h), color=(255,0,255), thickness=1)

line\_items\_coordinates.append([(x,y), (x+w, y+h)])

return image, line\_items\_coordinates

#define the mark\_region method

FILENAME = r"images1.jpeg" # \<— change this to be the file you want

image, line\_items\_coordinates = mark\_region(FILENAME)

plt.figure(figsize=(20,20))

plt.imshow(image)

plt.savefig(“image-with-regions.png”) # \<— added this to output an image

mark\_region

**Original image:**

 ![images1](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/4/458c8557acc2d628abd5a8ad3af2a39a46dd7af4.jpeg)
