straightening contoured rectangles in opencv python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



straightening contoured rectangles in opencv python



I have these images of ICs, on which i have to do some image processing. I am able to find the contour of these images. But sometimes these ICs are rotated randomly. How do I straighten them to a proper regular rectangle?



These are some of my contour detected images:



enter image description hereenter image description here



Will be glad, if anyone can get me started on how to rotate back these images to straight rectangle/squares. Thanks in advance :)





Hint: minAreaRect on the contour, and then rotate. Search around, there are many examples available on how to use those functions, both here on SO as well as on the web in general.
– Dan Mašek
Mar 18 '17 at 20:56


minAreaRect


rotate





this may get you started: docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/…
– ZdaR
Mar 19 '17 at 5:29




1 Answer
1



Here the code that solves your problem:


import cv2
import numpy as np

# get the minimum bounding box for the chip image
image = cv2.imread("./chip1.png", cv2.IMREAD_COLOR)
image = image[10:-10,10:-10]
imgray = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)[...,0]
ret, thresh = cv2.threshold(imgray, 20, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
mask = 255 - thresh
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

maxArea = 0
best = None
for contour in contours:
area = cv2.contourArea(contour)
if area > maxArea :
maxArea = area
best = contour

rect = cv2.minAreaRect(best)
box = cv2.boxPoints(rect)
box = np.int0(box)

#crop image inside bounding box
scale = 1 # cropping margin, 1 == no margin
W = rect[1][0]
H = rect[1][1]

Xs = [i[0] for i in box]
Ys = [i[1] for i in box]
x1 = min(Xs)
x2 = max(Xs)
y1 = min(Ys)
y2 = max(Ys)

angle = rect[2]
rotated = False
if angle < -45:
angle += 90
rotated = True

center = (int((x1+x2)/2), int((y1+y2)/2))
size = (int(scale*(x2-x1)), int(scale*(y2-y1)))

M = cv2.getRotationMatrix2D((size[0]/2, size[1]/2), angle, 1.0)

cropped = cv2.getRectSubPix(image, size, center)
cropped = cv2.warpAffine(cropped, M, size)

croppedW = W if not rotated else H
croppedH = H if not rotated else W

image = cv2.getRectSubPix(
cropped, (int(croppedW*scale), int(croppedH*scale)), (size[0]/2, size[1]/2))

# show result
while True:
cv2.imshow("result", image)
k = cv2.waitKey(30) & 0xff
if k == 27:
break



here the result image:
chip rectified






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered