MeasurementTesting / pixelconversion.py
Marthee's picture
Update pixelconversion.py
50d22ba
raw
history blame
3.93 kB
# -*- coding: utf-8 -*-
"""pixelconversion.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1hfdgkYOw8w6DdJqsZx8txmw8INUGxesl
"""
# pip install pymupdf -q
"""### Imports"""
import fitz
from PIL import Image
import numpy as np
import cv2
import db
"""### Open PDF and draw a rectangle on it using Fitz"""
def openDrawPDF(path):
doc = fitz.open(path)
out = fitz.open() # output PDF
page = doc[0]
print(page.rotation)
pix = page.get_pixmap() # render page to an image
pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
img=np.array(pl)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
ratio = pix.width / img.shape[1]
imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgBW=cv2.threshold(imgGry, 250, 255, cv2.THRESH_BINARY_INV)[1]
contours, hierarchy = cv2.findContours(imgBW, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
newcontours = contours[2:]
areas = [cv2.contourArea(c) for c in newcontours]
max_index2 = np.argmax(areas)
contour=newcontours[max_index2]
area=cv2.contourArea(contour)
if area >500:
perimeter = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.01* perimeter, True)
shape=[]
for point in approx:
x1, y1 = point[0]
shape.append([(int(x1*ratio)),(int(y1*ratio))])
cv2.circle (img, (x1, y1), 5, 255, 5)
rotate=0
if page.rect.height > page.rect.width:
rectText=fitz.Rect(300, 200, (page.rect.width-80),( page.rect.width+80) )
rotate=0
else:
rectText=fitz.Rect(500, 200, (page.rect.height-80),( page.rect.height+80) )
rotate=90
if page.rotation !=0:
rect = fitz.Rect(shape[0][1],shape[0][0],shape[2][1],shape[2][0])
else:
rect= fitz.Rect(shape[0][0],shape[0][1],shape[2][0],shape[2][1])
annot = page.add_rect_annot( rect=rect ) # 'rectangle'
annot.set_colors( fill=(75/255,0,130/255) ,stroke=(75/255,0,130/255) )
annot.set_opacity(0.9)
annot.set_border(border=None, width=0)
annot.update()
text = """Scale Document"""
annot1=page.add_freetext_annot(rectText, text, fontsize=45, fontname='helv', border_color=(1,1,1), text_color=(1,1,1), rotate=rotate, align=1)
annot1.update()
return doc
"""### Extract color"""
def DetectColor(img,color=0):
imgCopy=img.copy()
imgCopy=cv2.cvtColor(imgCopy,cv2.COLOR_BGR2HSV)
tol=5 #tolerance
# color=hexRGB(color)
h,s,v = cv2.cvtColor(np.uint8([[[color[2],color[1],color[0]]]]),cv2.COLOR_BGR2HSV)[0][0]
lower =np.array( [h- tol, 100, 100 ], dtype='uint8')
upper = np.array( [h + tol, 255, 255],dtype='uint8')
mask = cv2.inRange(imgCopy, lower , upper)
detectedColors = cv2.bitwise_and(imgCopy,imgCopy, mask= mask) # Bitwise-AND mask and original image
kernel=np.ones((3,3),np.uint8)
mask=cv2.dilate(mask,kernel, iterations=5)
mask=cv2.erode(mask,kernel, iterations=4)
detectedColors=cv2.dilate(detectedColors,kernel, iterations=5)
detectedColors=cv2.erode(detectedColors,kernel, iterations=4)
detectedColors=cv2.cvtColor(detectedColors,cv2.COLOR_HSV2BGR)
detectedColors=cv2.medianBlur(detectedColors,7)
# cv2_imshow(detectedColors)
return mask
"""### For backend - calc area and perim"""
def getAreaPerimeter(pdfpath, plan):
dbx=db.dropbox_connect()
md, res =dbx.files_download(path= pdfpath+plan)
data = res.content
doc=fitz.open("pdf", data)
for page in doc:
pix = page.get_pixmap(dpi=200) # render page to an image
pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
img=np.array(pl)
print(img.shape)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
mask=DetectColor(img,color=(73,0,130)) #detect colored rect drawn on the pdf
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
perimeter = cv2.arcLength(contour, True)
return area,perimeter