I want to predict rectangle in the image and draw the rectangle in box shape only using opencv python. i used below code for predict and draw rectangle but its not working properly.
import numpy as np
import cv2
from PIL import Image
import sys
Path='D:Artificial intelligencePhyton'
filename='Test.png'
# Load image, grayscale, Gaussian blur, and Otsu's threshold
image = cv2.imread('D:Artificial intelligencePhytonImg21122020113231AM.Jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 190, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find contours and sort using contour area
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
# Highlight largest contour
cv2.drawContours(image, [c], -1, (36,255,12), 3)
break
cv2.imwrite(filename+'_Processingimage_color.jpg', image)
My Input Image :
My Result :
2
Answers
For the shape-detection there is a great-tutorial called opencv-shape-detection. However the pre-processing in the tutorial won’t help you to find the big-box in the image. You need to apply
adaptiveThreshold
insteadthreshold
. Here are the steps:Step-1
Step-2
We applied gaussian-blur to smooth the image. Most of the artifacts in the image was removed.
Step-3
Simple-thresholding was not producing satisfactory results with different parameters. Therefore I used
adaptiveThreshold
to get the result:Step-4
Step-5
Step-6
If the approximation length is equals to 4, draw the contour. Result will be:
Code:
You should be able to detect your cardboard box in this particular image by following the below steps. You should be able to do all of this with numpy and OpenCV. It will be a lot of work though, so I haven’t done it. If someone else wants to go through with it and provide the source code, feel free to mark their answer as the correct one and not this one.
This stackoverflow post will help with step 7:
How to force approxPolyDP() to return only the best 4 corners? – Opencv 2.4.2
Another alternative potential solution to the method I outlined above (after detecting the brown cardboard color) can be found here:
Extracting the dimensions of a rectangle