reportlab use for loop to create multiple tables - python

I need through a for loop to create more tables, I think it works but I need to change the various coordinates, how can I do?
2)
Is it possible to change the width of a single row of a table? or in any case bring its text-align to the left but which starts from where the table starts?
def testPdfView(request, id):
#dati init
scheda = get_object_or_404(Schede, pk = id)
filename = 'media/pdf/' + scheda.nome_scheda + '.pdf'
titolo = scheda.utente.username + ' - ' + scheda.nome_scheda
#creazione file
doc = SimpleDocTemplate(
filename,
pagesize = A4,
rightMargin = 10*mm,
leftMargin = 10*mm,
topMargin = 47*mm,
bottomMargin = 10*mm
)
#titolo
doc.title = titolo
#passaggio scheda alla funzione pdfCanvas
doc.scheda = scheda
#table gruppi
gruppi = DatiGruppi.objects.filter(gruppi_scheda = id)
for gruppo in gruppi:
table = Table([
[str(gruppo).upper()]
], colWidths= 180*mm, repeatRows=1)
#table style
style = TableStyle([
('TEXTCOLOR', (0,0),(-1,0), colors.HexColor("#9FFC0D")),# -1 significa l'ultimo elemento
('FONTNAME', (0,0), (0,0), 'bulk_bold'),
('FONTSIZE', (0,0), (0,0), 6*mm),
('BOTTOMPADDING', (0,0), (-1,0), 6*mm),
('LINEBELOW',(0,0),(-1,0), 1, colors.HexColor("#9FFC0D")),
])
table.setStyle(style)
#table add to template
elems = []
elems.append(table)
#create
doc.build(elems, onFirstPage = pdfCanvas)

def genGroupTable(gruppo):
groupElemTeble = None
#tab
titleTable = Table([
[str(gruppo).upper(), str(gruppo.giorni_settimana).upper()]
], colWidths= 95*mm)
titleTable_style = TableStyle([
('TEXTCOLOR', (0,0),(-1,0), colors.HexColor("#9FFC0D")),
('FONTNAME', (0,0), (0,0), 'bulk_bold'),
('ALIGN',(1,0),(-1,0),'RIGHT'),
('VALIGN',(0,0),(-1,0),'MIDDLE'),
('FONTSIZE', (0,0), (0,0), 6*mm),
('BOTTOMPADDING', (0,0), (0,0), 6*mm),
('LINEBELOW',(0,0),(-1,0), 1, colors.HexColor("#9FFC0D")),
('LEFTPADDING',(0,0),(-1,-1), 0*mm),
('RIGHTPADDING',(0,0),(-1,-1), 0*mm)
])
titleTable.setStyle(titleTable_style)
thead = Table([
['ESERCIZIO','SERIE','RIPETIZIONI','PESO']
], colWidths= 47.5*mm)
thead_style = TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor("#19212A")),
('TEXTCOLOR', (0,0),(-1,0), colors.HexColor("#ffffff")),
('FONTNAME', (0,0), (-1,0), 'bulk_testo'),
('ALIGN',(0,0),(-1,0),'CENTER'),
('VALIGN',(0,0),(-1,0),'MIDDLE'),
('BOTTOMPADDING', (0,0), (-1,0), 1*mm)
])
thead.setStyle(thead_style)
exercise = []
elementi = []
for esercizio in gruppo.gruppo_single.all():
exercise.append(esercizio)
for es in range(len(exercise)):
tbody = Table([
[str(exercise[es]).upper(), str(exercise[es].serie).upper(), str(exercise[es].ripetizione).upper(), str(exercise[es].peso).upper()+'KG']
], colWidths= 47.5*mm)
tbody_style = TableStyle([
('TEXTCOLOR', (0,0),(-1,-1), colors.HexColor("#ffffff")),
('FONTNAME', (0,0), (-1,-1), 'bulk_testo'),
('ALIGN',(0,0),(-1,-1),'CENTER'),
('BOTTOMPADDING', (0,0), (-1,-1), 1*mm),
('LINEBELOW',(0,0),(-1,-1), .2, colors.HexColor("#ffffff"))
])
tbody.setStyle(tbody_style)
elementi.append(tbody)
#tab finale
groupElemTeble = Table([
[titleTable],
[thead],
[[elementi]]
], colWidths = 190*mm)
groupElemTeble_style = TableStyle([
#('BACKGROUND', (0, 0), (-1, -1), colors.HexColor("#202B38")),
('LEFTPADDING',(0,0),(-1,-1), 0*mm),
('RIGHTPADDING',(0,0),(-1,-1), 0*mm),
('BOTTOMPADDING',(-1,-1),(-1,-1), 5*mm)
])
groupElemTeble.setStyle(groupElemTeble_style)
return groupElemTeble
def testPdfView(request, id):
#dati init
scheda = get_object_or_404(Schede, pk = id)
filename = 'media/pdf/' + scheda.nome_scheda + '.pdf'
titolo = scheda.utente.username + ' - ' + scheda.nome_scheda
#creazione file
doc = SimpleDocTemplate(
filename,
pagesize = A4,
rightMargin = 10*mm,
leftMargin = 10*mm,
topMargin = 47*mm,
bottomMargin = 10*mm
)
#titolo
doc.title = titolo
#passaggio scheda alla funzione pdfCanvas
doc.scheda = scheda
#elemento vuoto
elems = []
#lista gruppi
group = []
gruppi = DatiGruppi.objects.filter(gruppi_scheda = id)
for gruppo in gruppi:
group.append(gruppo)
for gr in range(len(group)):
main = genGroupTable(group[gr])
elems.append(main)
#create
doc.multiBuild(elems, onFirstPage = header)
#return
percorso = str(settings.BASE_DIR) +'/media/pdf/' + scheda.nome_scheda + '.pdf'
return FileResponse(open(percorso, 'rb'), content_type='application/pdf')

Related

Python Reportlab - Wordwrap on Table is splitting words rather than at spaces

I created a PDF in reportlab using a canvas:
self.pdf = canvas.Canvas(f'{file_name}.pdf', pagesize=A4)
I create tables within tables to create my document but one of my tables is not wrapping the way I expect it to. Rather than linebreaking at spaces, it does so between words as seen below.
The code below is the code I used to create the table. It is a bit long as I did make sure that the cells I'm passing into the Table() are all Paragraph().
def _discount_table(self, width_list):
# Table Name
table_name = Paragraph('DISCOUNTS', self.header_style_grey)
# Create Header
header = [Paragraph('NAME', self.table_header_style_left)]
header += [Paragraph(x, self.table_header_style_right) for x in self.unique_discount_list]
header += [Paragraph('TOTAL', self.table_header_style_right)]
# Process Data
discount_data = [[Paragraph(cell, self.table_style2) for cell in row] for row in self.discount_data]
data = [[child_row[0]] + disc for child_row, disc in zip(self.fees_data, discount_data)]
# Create Footer
table_footer = [Paragraph('') for _ in range(len(header) - 2)]
table_footer += [Paragraph('TOTAL', self.table_header_style_right),
Paragraph(f'{self.discount_total:,.2f}', self.table_header_style_right)]
# Create Table
bg_color = self.header_style_grey.textColor
table = Table([header] + data + [table_footer], colWidths=width_list)
table.setStyle([
('GRID', (0, 0), (-1, -1), 1, 'black'),
('BACKGROUND', (0, 0), (-1, 0), bg_color),
('TEXTCOLOR', (0, 0), (-1, 0), 'white'),
('BACKGROUND', (-2, -1), (-1, -1), bg_color),
('TEXTCOLOR', (-2, -1), (-1, -1), 'white'),
('FONTNAME', (-2, -1), (-1, -1), 'Helvetica-Bold'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
('ROWBACKGROUNDS', (0, 1), (-1, -2), ['lightgrey', 'white']),
])
return [table_name, table]
(To note that child_row[0] is already a Paragraph - this is found on the line 12 above)
The styling I used is imported from another python file as follows:
self.table_style2 = ParagraphStyle('table_style')
self.table_style2.wordWrap = 'CJK'
self.table_style2.alignment = TA_RIGHT
self.table_style = ParagraphStyle('table_style')
self.table_style.wordWrap = 'CJK'
self.table_header_style_right = ParagraphStyle('table_header_style', self.table_style)
self.table_header_style_right.textColor = colors.HexColor('#FFFFFF')
self.table_header_style_right.fontName = 'Helvetica-Bold'
self.table_header_style_right.alignment = TA_RIGHT
self.table_header_style_right.wordWrap = 'CJK'
self.table_header_style_left = ParagraphStyle('table_header_style', self.table_style)
self.table_header_style_left.textColor = colors.HexColor('#FFFFFF')
self.table_header_style_left.fontName = 'Helvetica-Bold'
self.table_header_style_left.wordWrap = 'CJK'
So I am really lost and need help. Why is the table not wrapping correctly?
I was able to fix the table wrap issue when I removed the wordWrap = 'CJK' portion of the code. I saw in a video that a Paragraph() will automatically wordWrap so I'm guessing there was some issue with how those two elements overlap
self.table_style2 = ParagraphStyle('table_style')
# self.table_style2.wordWrap = 'CJK'
self.table_style2.alignment = TA_RIGHT
self.table_style = ParagraphStyle('table_style')
# self.table_style.wordWrap = 'CJK'
self.table_header_style_right = ParagraphStyle('table_header_style', self.table_style)
self.table_header_style_right.textColor = colors.HexColor('#FFFFFF')
self.table_header_style_right.fontName = 'Helvetica-Bold'
self.table_header_style_right.alignment = TA_RIGHT
# self.table_header_style_right.wordWrap = 'CJK'
self.table_header_style_left = ParagraphStyle('table_header_style', self.table_style)
self.table_header_style_left.textColor = colors.HexColor('#FFFFFF')
self.table_header_style_left.fontName = 'Helvetica-Bold'
# self.table_header_style_left.wordWrap = 'CJK'

pdfencrypt with Reportlab

I want to add password protection for opening the pdf file from a Django project.
def pdf_view(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="members.pdf"'
elements = []
doc = SimpleDocTemplate(response, rightMargin=0.5 * cm, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
rows = []
users = User.objects.all()
for user in users:
rows.append((
user.username,
user.email,
user.first_name,
user.last_name,
formats.date_format(user.date_joined, "SHORT_DATETIME_FORMAT"),
formats.date_format(user.subscriptions.current_period_end, "SHORT_DATETIME_FORMAT")
))
table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
table.setStyle([
('GRID', (0, 0), (-1, -1), 0.25, colors.black),
("ALIGN", (0, 0), (-1, -1), "LEFT"),
])
table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
elements.append(table)
doc.build(elements)
return response
where can I add this line of code to do encryption
pdfencrypt.StandardEncryption("password", canPrint=0)
any help will be much appreciated
you can add the line of code as below
def pdf_view(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="members.pdf"'
elements = []
**doc = SimpleDocTemplate(response, encrypt=pdfencrypt.StandardEncryption("pass", canPrint=0)**, rightMargin=0.5 * cm, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
rows = []
users = User.objects.all()
for user in users:
rows.append((
user.username,
user.email,
user.first_name,
user.last_name,
formats.date_format(user.date_joined, "SHORT_DATETIME_FORMAT"),
formats.date_format(user.subscriptions.current_period_end, "SHORT_DATETIME_FORMAT")
))
table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
table.setStyle([
('GRID', (0, 0), (-1, -1), 0.25, colors.black),
("ALIGN", (0, 0), (-1, -1), "LEFT"),
])
table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1)
elements.append(table)
doc.build(elements)
return response

braidTool_Maya_script_error # NameError: name 'QtGui' is not defined

I found someone else's braid tool online and it seems to be working for other people but it doesn't for me. I can't reach that person for help so I am posting here instead.
There's 2 scripts, one is the actual making of the braid and the other is for loading UI. I keep getting The following error:
# Error: Traceback (most recent call last):
# File "<maya console>", line 2, in <module>
# File "/home/ykim/private/maya/2018/scripts/JUM/scripts/braid.py", line 12, in <module>
# list_form, list_base = load_ui_type(ui_file)
# File "/home/ykim/private/maya/2018/scripts/JUM/core/loadUIFile.py", line 30, in load_ui_type
# form_class = frame['Ui_{0}'.format(form_class)]
# File "<string>", line 1, in <module>
# NameError: name 'QtGui' is not defined
#
The following is the 1st script making the braid
import os
from JUM.core.loadUIFile import get_maya_window, load_ui_type
import random
import maya.cmds as cmds
ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'UI','braid.ui')
list_form, list_base = load_ui_type(ui_file)
class espiral(list_form, list_base):
def __init__(self, parent = get_maya_window()):
self.__radius = 0.0
self.__side = 6
self.__variation = 0
self.__circle = ''
self.__pt_position_A = []
self.__pt_position_B = []
self.__pt_position_C = []
self.__path = ''
self.__quantidade = 0.0
self.clock = True
##########################################################
# #
# UI elements #
# #
##########################################################
self.window_name = 'makeSpiralWin'
if cmds.window(self.window_name, exists = True):
cmds.deleteUI(self.window_name)
super(espiral, self).__init__(parent)
self.setupUi(self)
self.btn_selectPath.clicked.connect(self.getPath)
self.btn_create.setDisabled(True)
self.btn_create.clicked.connect(self.create)
def __makeEight(self):
side = 16
offset = self.spin_offset.value()
eight = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), degree=3, sections=side)
cmds.select(eight[0])
lattice = cmds.lattice(dv = (3, 2, 3), objectCentered = True )
cmds.setAttr(lattice[0]+'.local', 0)
cmds.select(lattice[1]+'.pt[2][0:1][0]',lattice[1]+'.pt[2][0:1][1]',lattice[1]+'.pt[2][0:1][2]')
cmds.scale(1, 1, -1, pivot = (1.108194, 0 , 0), relative = True)
cmds.select(lattice[1]+'.pt[1][0:1][0]',lattice[1]+'.pt[1][0:1][1]',lattice[1]+'.pt[1][0:1][2]')
cmds.scale(0, 0, 0, pivot = (0, 0 , 0), relative = True)
cmds.select(lattice[1]+'.pt[0][0:1][0]',lattice[1]+'.pt[2][0:1][2]',lattice[1]+'.pt[2][0:1][0]',lattice[1]+'.pt[0][0:1][2]')
cmds.scale(1, 1, 1.455556, pivot = (0, 0 , 0), relative = True)
cmds.scale(0.929167, 1, 1, pivot = (0, 0 , 0), relative = True)
cmds.select(eight[0])
cmds.delete(ch = True)
cmds.rotate(0,offset,0,eight[0])
cmds.makeIdentity(eight[0],apply = True, t = True, r = True, s = True, n = 0, pn = True)
return eight
def __next(self, porcentagem,eight,scale):
#print porcentagem
curva = self.ln_path.text()
position = cmds.pointOnCurve(curva, top=True, pr=porcentagem, position=True)
tangent = cmds.pointOnCurve(curva, top=True, pr=porcentagem, tangent=True)
angle = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)
cmds.scale((scale * random.uniform((1-self.spin_random.value()), 1.0)),
(scale * random.uniform((1-self.spin_random.value()), 1.0)),
(scale * random.uniform((1-self.spin_random.value()), 1.0)),
eight[0])
cmds.move(position[0],
position[1],
position[2],
eight[0])
cmds.rotate(angle[0],
angle[1],
angle[2],
eight[0])
def __voltas(self):
steps = 16 * float(self.spin_loops.value())
porcent = 1.0 / steps
return int(steps), porcent
def __makeMesh(self,curva):
scale_0 = self.spin_radius.value()
scale_1 = self.spin_radius_1.value()
scale = self.spin_radius.value()
if (scale_0 >= scale_1):
tempMaior = scale_0
tempMenor = scale_1
else:
tempMaior = scale_1
tempMenor = scale_0
scale_extrude = tempMenor/tempMaior
position = cmds.pointOnCurve(curva, top=True, pr=0, position=True)
tangent = cmds.pointOnCurve(curva, top=True, pr=0, normalizedTangent=True)
angle = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)
circle = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), degree=3, sections=16, r = 0.5)
cmds.scale(tempMaior,
tempMaior,
tempMaior,
circle[0])
cmds.move(position[0],
position[1],
position[2],
circle[0])
cmds.rotate(angle[0],
angle[1],
angle[2],
circle[0])
extrude = cmds.extrude(circle[0],
curva,
constructionHistory = True,
range = True,
polygon = 0,
extrudeType = 2,
useComponentPivot = 0,
fixedPath = 0,
useProfileNormal = 1,
rotation = 0,
scale = scale_extrude,
reverseSurfaceIfPathReversed = 1)
poly = cmds.nurbsToPoly(extrude[0], matchNormalDir = True, constructionHistory = False, format = 2, polygonType = 1, uType = 3, uNumber = 1, vType = 3, vNumber = 3)
cmds.delete(circle, extrude[0])
print poly
return poly
def __curve(self):
curve_A = cmds.curve(p=self.__pt_position_A)
curve_B = cmds.curve(p=self.__pt_position_B)
curve_C = cmds.curve(p=self.__pt_position_C)
if (self.btn_makeMesh.isChecked()):
mesh_A = self.__makeMesh(curve_A)
mesh_B = self.__makeMesh(curve_B)
mesh_C = self.__makeMesh(curve_C)
cmds.delete(curve_A, curve_B, curve_C)
cmds.select(mesh_A,mesh_B,mesh_C)
else:
cmds.select(curve_A,curve_B,curve_C)
def __braid(self):
steps, porcent = self.__voltas()
increment = porcent
eight = self.__makeEight()
list = range(int(steps))
offset = self.spin_offset.value()
offset_normalize = offset/360.0
self.progress_Create.setRange(0,len(list))
scale_0 = self.spin_radius.value()
scale_1 = self.spin_radius_1.value()
if (scale_0 >= scale_1):
scale_maior = scale_0
scale_menor = scale_1
else:
scale_maior = scale_1
scale_menor = scale_0
diference = scale_maior-scale_menor
percent = diference/steps
scale = scale_maior
if (self.btn_reverse.isChecked()):
curva = self.ln_path.text()
cmds.reverseCurve(curva,ch = False, replaceOriginal = True)
for i in list:
self.progress_Create.setValue(i)
self.__next(porcent,eight,scale)
porcent += increment
_pos_A = (i*0.0625)%1.0 + offset_normalize
_pos_B = (i*0.0625+0.333333)%1.0 + offset_normalize
_pos_C = (i*0.0625+0.666666666)%1.0 + offset_normalize
self.__pt_position_A.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_A, p=True ))
self.__pt_position_B.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_B, p=True ))
self.__pt_position_C.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_C, p=True ))
scale -= percent
self.progress_Create.reset()
#cmds.delete(self.__circle[0])
# return self.__pt_position
self.__curve()
cmds.delete(eight[0])
def getPath(self):
path = cmds.ls(sl = True)
if path == []:
self.ln_path.setText('Nothing selected')
self.btn_create.setDisabled(True)
self.ln_path.setStyleSheet("background-color: rgb(110, 90, 90);")
else:
shape_path = cmds.listRelatives(path[0])
if (cmds.objectType(shape_path)== 'nurbsCurve'):
self.ln_path.setText(path[0])
self.btn_create.setEnabled(True)
self.ln_path.setStyleSheet("background-color: rgb(90, 150, 50);")
else:
self.ln_path.setText('Path not valid')
self.btn_create.setDisabled(True)
self.ln_path.setStyleSheet("background-color: rgb(110, 90, 90);")
def create(self):
self.__braid()
self.__pt_position_A = []
self.__pt_position_B = []
self.__pt_position_C = []
def run():
espira = espiral()
espira.show()
Another script is for loading UI design
import shiboken2
from PySide2 import QtWidgets
from PySide2 import QtGui
import maya.OpenMayaUI as apiUI
from cStringIO import StringIO
import pyside2uic
import xml.etree.ElementTree as xml
def get_maya_window():
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)
def load_ui_type(ui_file):
parsed = xml.parse(ui_file)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(ui_file,'r') as f:
o = StringIO()
frame = {}
pysideu2ic.compileUi(f, o, indent = 0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec pyc in frame
# Fetch the base_class and form class based on their type in the xml from design
form_class = frame['Ui_{0}'.format(form_class)]
base_class = eval('QtGui.{0}'.format(widget_class))
return form_class, base_class

Unable to write image in PDF File

def logo_para(self):
exp = Paragraph(
'<b>Express</b>', self.styles['CenterHeading'])
csheet = Paragraph(
'<b>PDF SHEET</b>', self.styles['CenterHeading'])
img_location = "https://www.google.co.in/logos/doodles/2016/icc-australia-v-bangladesh-5759441086447616-res.png"
img_data = '''
<para><img src="%s" width="300" height="90"/><br/>
</para>''' % img_location
img = Paragraph(img_data, self.styles['CenterHeading'])
data = [[exp], [csheet], [''], [img] ]
main_header_table = Table([['', img, '']], colWidths=(100, 300, 100))
main_header_table.setStyle(TableStyle([
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('BOX', (0, 0), (-1, -1), 0.25, colors.black)
]))
self.elements.append(main_header_table)
When ever I am calling
docket.logo_para()
I am getting error cannot concatenate 'str' and 'int' objects
at self.doc.build(self.elements)
When the line is commenteddocket.logo_para(), the code works superbly.
I am trying to add an image on the PDF File using SimpleDocTemplate
EDIT 1
creating new pdf
class PDFDocketGenerator(object):
def __init__(self, file_name):
self.filename = file_name
self.filepath = STATIC_URL + 'uploads/billing/' + file_name
self.path_to_save = FILE_UPLOAD_TEMP_DIR + '/billing/' + file_name
# define the pdf object
self.doc = SimpleDocTemplate(
self.path_to_save, pagesize=landscape(A4), topMargin=50, bottomMargin=30,
leftMargin=60, rightMargin=60)
self.elements = []
writing to pdf
def write_pdf(self):
self.doc.build(self.elements)
Is it possible that some values in self.elements are integers? I would suggest to try this in this case :
def write_pdf(self):
self.doc.build([str(e) for e in self.elements])

3d reconstruction and distance measurment

hi guys I have been working on a small program in python using the opencv library and two webcams so that I can measure the distance between this last tow and the object right in front of them(using the disparity map) ,so when I run the program at the end I normally I get the result in a matrix but what I get is not only one number(which is supposed to be the distance) but many different numbers,besides I always get one number which doesn't change even if I change the view can any body tell me why?!
here is the code:
import numpy as np
import cv2 as cv
import cv2.cv as cv1
from VideoCapture import Device
import os
def caliLeftCam():
args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
args = dict(args)
try: img_mask = img_mask[0]
except: img_mask = '../cpp/img*.jpg'
img_names = glob(img_mask)
debug_dir = args.get('--debug')
square_size = float(args.get('--square_size', 1.0))
pattern_size = (7, 5)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_pointsL = []
h, w = 0, 0
for fn in img_names:
print "processing %s..." % fn,
imgL = cv.imread(fn, 0)
h, w = imgL.shape[:2]
found, corners = cv.findChessboardCorners(imgL, pattern_size)
if found:
term = ( cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1 )
cv.cornerSubPix(imgL, corners, (5, 5), (-1, -1), term)
if debug_dir:
vis = cv.cvtColor(imgL, cv.COLOR_GRAY2BGR)
cv.drawChessboardCorners(vis, pattern_size, corners, found)
path, name, ext = splitfn(fn)
cv.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
if not found:
print "chessboard not found"
continue
img_pointsL.append(corners.reshape(-1, 2))
obj_points.append(pattern_points)
print 'ok'
rmsL, cameraL_matrix, dist_coefsL, rvecsL, tvecsL = cv.calibrateCamera(obj_points, img_pointsL, (w, h))
print "RMSL:", rmsL
print "Left camera matrix:\n", cameraL_matrix
print "distortion coefficients: ", dist_coefsL.ravel()
newcameramtxL, roi=cv.getOptimalNewCameraMatrix(cameraL_matrix,dist_coefsL,(w,h),1,(w,h))
#undistort
mapxL,mapyL = cv.initUndistortRectifyMap(cameraL_matrix,dist_coefsL,None,newcameramtxL,(w,h),5)
dstL = cv.remap(imgL,mapxL,mapyL,cv.INTER_LINEAR)
return img_pointsL, cameraL_matrix, dist_coefsL
def caliRightCam():
args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
args = dict(args)
try: img_mask = img_mask[0]
except: img_mask = '../cpp/ph*.jpg'
img_names = glob(img_mask)
debug_dir = args.get('--debug')
square_size = float(args.get('--square_size', 1.0))
pattern_size = (7, 5)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_pointsR = []
h, w = 0, 0
for fn in img_names:
print "processing %s..." % fn,
imgR = cv.imread(fn, 0)
h, w = imgR.shape[:2]
found, corners = cv.findChessboardCorners(imgR, pattern_size)
if found:
term = ( cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1 )
cv.cornerSubPix(imgR, corners, (5, 5), (-1, -1), term)
if debug_dir:
vis = cv.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv.drawChessboardCorners(vis, pattern_size, corners, found)
path, name, ext = splitfn(fn)
cv.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
if not found:
print "chessboard not found"
continue
img_pointsR.append(corners.reshape(-1, 2))
obj_points.append(pattern_points)
print 'ok'
rmsR, cameraR_matrix, dist_coefsR, rvecsR, tvecsR = cv.calibrateCamera(obj_points, img_pointsR, (w, h))
print "RMSR:", rmsR
print "Right camera matrix:\n", cameraR_matrix
print "distortion coefficients: ", dist_coefsR.ravel()
newcameramtxR, roi=cv.getOptimalNewCameraMatrix(cameraR_matrix,dist_coefsR,(w,h),1,(w,h))
# undistort
mapxR,mapyR = cv.initUndistortRectifyMap(cameraR_matrix,dist_coefsR,None,newcameramtxR,(w,h),5)
dstR = cv.remap(imgR,mapxR,mapyR,cv.INTER_LINEAR)
return img_pointsR,obj_points, cameraR_matrix, dist_coefsR
def Pics():
vc = cv.VideoCapture(2)
retVal, frame = vc.read();
while True :
if frame is not None:
imgray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(imgray,127,255,1)
contours, hierarchy = cv.findContours(thresh,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
cv.namedWindow("threshold")
cv.namedWindow("Camera")
#cv2.drawContours(frame, contours, -1, (0,255,0), 2)
cv.imshow("Camera", frame)
cv.imshow("threshold", thresh)
rval, frame = vc.read()
if cv.waitKey(1) & 0xFF == 27:
break
cv1.DestroyAllWindows()
def LeftCap():
cam = Device(2)
cam.saveSnapshot('imageL.jpg')
fn = 'C:\opencv2.4.8\sources\samples\python2\imageL.jpg'
return fn
def RightCap():
cam = Device(0)
cam.saveSnapshot('imageR.jpg')
fn = 'C:\opencv2.4.8\sources\samples\python2\imageR.jpg'
return fn
def Calculate(Li, Ri, Mat):
img_L = cv.pyrDown( cv.imread(Li) )
img_R = cv.pyrDown( cv.imread(Ri) )
window_size = 3
min_disp = 16
num_disp = 112-min_disp
stereo = cv.StereoSGBM(minDisparity = min_disp,
numDisparities = num_disp,
SADWindowSize = window_size,
uniquenessRatio = 10,
speckleWindowSize = 100,
speckleRange = 32,
disp12MaxDiff = 1,
P1 = 8*3*window_size**2,
P2 = 32*3*window_size**2,
fullDP = False
)
print "computing disparity..."
disp = stereo.compute(img_L, img_R).astype(np.float32) / 16.0
print "generating 3d point cloud..."
h, w = img_L.shape[:2]
f = 0.8*w # guess for focal length
points = cv.reprojectImageTo3D(disp, Mat)
colors = cv.cvtColor(img_L, cv.COLOR_BGR2RGB)
mask = disp > disp.min()
cv.imshow('left', img_L)
cv.imshow('disparity', (disp-min_disp)/num_disp)
b=6.50
D=b*f/disp
print "The Distance =", D
cv.waitKey()
cv1.DestroyAllWindows()
if __name__ == '__main__':
import sys, getopt
from glob import glob
Img_pointsL, Cam_MatL, DisL = caliLeftCam()
Img_pointsR,obj_points, Cam_MatR, DisR = caliRightCam()
print "Running stereo calibration..."
retval, Cam_MatL, DisL, Cam_MatR, DisR, R, T, E, F= cv.stereoCalibrate(obj_points, Img_pointsL, Img_pointsR,(384,288))
print"running rectifation..."
RL, Rr, PL, PR, Q, validRoiL, validRoiR = cv.stereoRectify(Cam_MatL, DisL, Cam_MatR, DisR,(384,288), R, T)
Pics()
Li = LeftCap()
Ri = RightCap()
Calculate(Li, Ri, Q)
Not sure if that is a problem, but you call cv.StereoRectify() function using cv2.StereoRectify() not cv2.cv.StefeoRectify() and you provided wrong arguments to it.
From documentation:
cv.StereoRectify(cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q=None, flags=CV_CALIB_ZERO_DISPARITY, alpha=-1, newImageSize=(0, 0))
You did it that(wrong) way:
cv.stereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2...)

Categories