Agisoft Metashape

Agisoft Metashape => Python and Java API => Topic started by: magic on November 13, 2017, 04:31:56 PM

Title: Add photos to the chunk
Post by: magic on November 13, 2017, 04:31:56 PM
hello
I'm trying to add whole folder to the Photoscan , i have 1k5 fotos and i dont know how to do it , i would like to load them all from my directory f:/photos and create several chunks (sort my fotos automatically by the time every 5min new repository(how we can do it with python script) or chunk or camera doesnt matter - I have 30minutes work inside thats mean i want 6 folders, each 5min works inside ), i would like to use python to go with my path direct to my repository and get fotos wivouth using a mouse,
will show u my code


to use date and time need to use exif -->>  camera.photo.meta['Exif/DateTimeOriginal']

import os, PhotoScan
doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk initial"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
Title: Re: Add fotos to the chunk
Post by: Alexey Pasumansky on November 13, 2017, 05:16:45 PM
Hello magic,

I could suggest something like the following:
Code: [Select]
import os, PhotoScan

doc = PhotoScan.app.document
chunk = doc.addChunk()

path_photos = PhotoScan.app.getExistingDirectory("Dosier images avec Exif:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
if photo.lower() in ["jpg", "jpeg", "tif", "tiff"]:
photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
This script should add the images from the user-defined folder to the new chunk (supported types are defined in the script body).
Title: Re: Add fotos to the chunk
Post by: magic on November 13, 2017, 06:09:49 PM
still cant load those photos , now iv got this :


2017-11-13 15:50:43 AddPhotos
2017-11-13 15:50:43 Finished processing in 0 sec (exit code 0)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-48-74982a19c57e> in <module>()
     10         if photo.lower() in ["jpg", "jpeg", "tif", "tiff"]:
     11                 photo_list.append("/".join([path_photos, photo]))
---> 12 chunk.addPhotos(photo_list)
     13

RuntimeError: Empty file list


Title: Re: Add fotos to the chunk
Post by: Alexey Pasumansky on November 13, 2017, 06:10:57 PM
Hello magic,

What's in path_photos variable and image_list?
Title: Re: Add fotos to the chunk
Post by: magic on November 13, 2017, 06:43:46 PM
thats the code

: import os, PhotoScan

doc = PhotoScan.app.document
chunk = doc.addChunk()

path_photos = PhotoScan.app.getExistingDirectory("F:\temp\photo")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
   if photo.lower() in ["jpg", "jpeg", "tif", "tiff"]:
      photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
Title: Re: Add fotos to the chunk
Post by: Alexey Pasumansky on November 13, 2017, 07:21:26 PM
Oh, I think I've got a mistake in the code, there should be:
Code: [Select]
if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
Title: Re: Add fotos to the chunk
Post by: magic on November 14, 2017, 11:20:28 AM
Hi Alexey

Thx its works now with that code i can load the photos and they go to Chunk and cameras folder all of them, did i can divide them and get them into this chunk but to several cameras (not into one) , i would like to import them and sort it by time

     etc...
Code: [Select]
import os, PhotoScan
doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk initial"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")


time_table = list()  ###traitement par temps avec exif-DateTimeOriginal
for camera in chunk.cameras:
time = camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", ".")
time = float(time)
time = time // 1 + (time  - time // 1) * 100 / 60
time_table.append(time)

time_table.sort()
limits = (time_table[0], time_table[-1])
interval = 10 / 60. ##### divisoin par X minutes choisis
start = limits[0]
while True:     #####condition traitement par temps si vrais
##### ajoute des photos trier par l'heure + creation chunk pour chaque morceux
new_chunk = chunk.copy()
finish = start + interval
new_chunk.label = "{:d}:{:d} - {:d}:{:d}".format(int(start // 1), int((start - start // 1) * 60),
int(finish // 1), int((finish - finish // 1) * 60))
for camera in list(new_chunk.cameras): ######for avec d temps exif
time = float(camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", "."))


break

print("script finished")
Title: Re: Add fotos to the chunk
Post by: Alexey Pasumansky on November 14, 2017, 02:34:04 PM
Hello magic,

Can you post the contents of camera.photo.meta - at least those tags that should be used to split the cameras. Also specify, if you need to have several camera groups in the same chunk or several chunks?
Title: Re: Add fotos to the chunk
Post by: magic on November 14, 2017, 04:15:02 PM
Hi Alexey

In meta iv got something like this
Code: [Select]
camera.photo.meta
Out[62]: 2017-11-14 13:42:02 {'Exif/DateTime': '2017:10:20 08:02:47', 'Exif/DateTimeOriginal': '2017:10:20 08:02:47', 'Exif/ExposureTime': '0.00625', 'Exif/FNumber': '0', 'Exif/FocalLength': '0', 'Exif/FocalLengthIn35mmFilm': '0', 'Exif/ISOSpeedRatings': '10000', 'Exif/Make': 'SONY', 'Exif/Model': 'ILCE-5100', 'Exif/Orientation': '1', 'Exif/Software': 'ILCE-5100 v3.10', 'File/ImageHeight': '4000', 'File/ImageWidth': '6000', 'System/FileModifyDate': '2017:10:20 08:02:46', 'System/FileSize': '7897088'}

And will be nice to split it into several chunks


Thx a lot Alexey but my python skills are very bad


thats my code for now :

Code: [Select]
import os, PhotoScan

doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk"




# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")




chunk = doc.addChunk()
chunk.label = "New Chunk 1"

# Ajout de photos - add photos 2nd chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")

print(">>> Script terminé <<<")
Title: Re: Add fotos to the chunk
Post by: magic on November 15, 2017, 12:49:24 PM
Hello Alexey

Any suggestion how to do it ?? I'm stuck can't figured out how i can do this
Title: Re: Add fotos to the chunk
Post by: Alexey Pasumansky on November 15, 2017, 06:31:57 PM
Hello magic,

I can suggest something as following:


Code: [Select]
doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")


time_table = list()
for camera in chunk.cameras:
time = camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", ".")
time = float(time)
time = time // 1 + (time  - time // 1) * 100 / 60
time_table.append(time)

time_table.sort()
limits = (time_table[0], time_table[-1])
interval = 5 / 60. #five minute interval
start = limits[0]

while True:

new_chunk = chunk.copy()
finish = start + interval
new_chunk.label = "{:d}:{:d} - {:d}:{:d}".format(int(start // 1), int((start - start // 1) * 60),
int(finish // 1), int((finish - finish // 1) * 60))#####
for camera in list(new_chunk.cameras):
time = float(camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", "."))
time = time // 1 + (time  - time // 1) * 100 / 60

if time < start:
new_chunk.remove(camera)
elif time >= start + interval:
new_chunk.remove(camera)

start += interval
if not len(new_chunk.cameras):
doc.remove(new_chunk)
if start > limits[-1]:
break

print("script finished")

Title: Re: Add photos to the chunk
Post by: magic on November 16, 2017, 12:07:31 PM
Hello Alexey

Thx a lot man U are the best its works !!!!!
Title: Re: Add photos to the chunk
Post by: magic on November 17, 2017, 11:48:16 AM
Hello Alexey

Its me again , iv been tried to modify this code to get same result but now with the cameras

Code: [Select]
import os, PhotoScan
doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk initial"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")


time_table = list()  ###traitement par temps avec exif-DateTimeOriginal
for camera in chunk.cameras:
time = camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", ".")
time = float(time)
time = time // 1 + (time  - time // 1) * 100 / 60
time_table.append(time)

time_table.sort()
limits = (time_table[0], time_table[-1])
interval = 10 / 60. ##### divisoin par X minutes choisis
start = limits[0]

while True:     #####condition traitement par temps si vrais
##### ajoute des photos trier par l'heure + creation chunk pour chaque morceux
new_cameras = cameras.copy()
finish = start + interval
new_camera.label = "{:d}:{:d} - {:d}:{:d}".format(int(start // 1), int((start - start // 1) * 60),
int(finish // 1), int((finish - finish // 1) * 60))
for camera in list(new_cameras.cameras): ######for avec d temps exif
time = float(camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", "."))
time = time // 1 + (time  - time // 1) * 100 / 60

if time < start: ####
new_cameras.remove(camera)
elif time >= start + interval:
new_cameras.remove(camera)

start += interval
if not len(new_cameras.cameras):
doc.remove(new_cameras)
if start > limits[-1]:
break

print("script finished")

what i have to modify overhere Alexey??
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 17, 2017, 12:01:37 PM
Hello magic,

Do you mean creation of the camera groups in the Workspace pane?
Title: Re: Add photos to the chunk
Post by: magic on November 17, 2017, 12:17:46 PM
like with code before benn loading photos by time to new chunks
chunk1
chunk2
chunk3
etc...
Code: [Select]
import os, PhotoScan
doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk initial"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")


time_table = list()  ###traitement par temps avec exif-DateTimeOriginal
for camera in chunk.cameras:
time = camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", ".")
time = float(time)
time = time // 1 + (time  - time // 1) * 100 / 60
time_table.append(time)

time_table.sort()
limits = (time_table[0], time_table[-1])
interval = 10 / 60. ##### divisoin par X minutes choisis
start = limits[0]

while True:     #####condition traitement par temps si vrais action
##### ajoute des photos trier par l'heure + creation chunk pour chaque morceux
new_chunk = chunk.copy()
finish = start + interval
new_chunk.label = "{:d}:{:d} - {:d}:{:d}".format(int(start // 1), int((start - start // 1) * 60),
int(finish // 1), int((finish - finish // 1) * 60))
for camera in list(new_chunk.cameras): ######for avec d temps exif
time = float(camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", "."))
time = time // 1 + (time  - time // 1) * 100 / 60

if time < start:
new_chunk.remove(camera)
elif time >= start + interval:
new_chunk.remove(camera)

start += interval
if not len(new_chunk.cameras):
doc.remove(new_chunk)
if start > limits[-1]:
break

print("script finished")


and iv tried now to do same but to load it to new cameras or groupe
something like :
chunk
     -cameras1
     -cameras2
     -cameras3
 etc
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 17, 2017, 01:59:47 PM
Hello magic,

I have updated the second part of the script - now it splits the cameras to the groups inside the single (active) chunk:
Code: [Select]
doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")


time_table = list()
for camera in chunk.cameras:
time = camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", ".")
time = float(time)
time = time // 1 + (time  - time // 1) * 100 / 60
time_table.append(time)

time_table.sort()
limits = (time_table[0], time_table[-1])
interval = 5 / 60. #five minute interval
start = limits[0]

while True:

empty = True
new_group = chunk.addCameraGroup()
finish = start + interval
new_group.label = "{:d}:{:d} - {:d}:{:d}".format(int(start // 1), int((start - start // 1) * 60),
int(finish // 1), int((finish - finish // 1) * 60))#####
for camera in list(chunk.cameras):
time = float(camera.photo.meta['Exif/DateTimeOriginal'].split(" ")[1][:-3].replace(":", "."))
time = time // 1 + (time  - time // 1) * 100 / 60

if start <= time < start + interval:
camera.group = new_group
empty = False

start += interval

if empty:
chunk.remove(new_group)
if start > limits[-1]:
break

print("script finished")
Title: Re: Add photos to the chunk
Post by: magic on November 17, 2017, 03:41:47 PM
it works well
thx Alexey
Title: Re: Add photos to the chunk
Post by: magic on November 22, 2017, 12:36:30 PM
Hello Alexey

Again some question to You , today i would like to disable several photos in my camera , iv got some script but with it i can only disabled or enabled all of my photos cant figured out how to do this, check my code
 to enable all of cameras:its works
Code: [Select]
import PhotoScan
doc = PhotoScan.app.document
chunk = doc.chunk

for camera in chunk.cameras:
if camera.enabled == False:
camera.enabled = True

print('cam dis')

and if i want to disabled every 5th camera in my cameras iv been tried those script:
Code: [Select]
import PhotoScan
doc = PhotoScan.app.document
chunk = doc.chunk
x = 0

for camera in chunk.cameras:
if camera.enabled == True:
camera.selected = False
x += 5
print('every 5th image is disabled ')

 and i have no error but no action as well ...
could you help with it pls

Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 22, 2017, 01:06:52 PM
Hello magic,

I can suggest the following:

Code: [Select]
import PhotoScan

chunk = PhotoScan.app.document.chunk
step = 5

for i in range(len(chunk.cameras)):
    camera = chunk.cameras[i]
    if not (i + 1) % step:
        camera.enabled = False
    else:
        camera.enabled = True
print("Every {:d} camera disabled.".format(step))
Title: Re: Add photos to the chunk
Post by: magic on November 22, 2017, 02:36:20 PM
Hi Alexey

Seems good but dsnt work, its something like no action inside , return print but any cameras picked in our list
Title: Re: Add photos to the chunk
Post by: magic on November 22, 2017, 02:51:48 PM
we have one action in Alexey this script going to disabled only one camera the last camera in cameras
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 22, 2017, 02:59:33 PM
Hello magic,

I have forgotten the camera assignment:
Code: [Select]
    camera = chunk.cameras[i]See the updated script in the post above.
Title: Re: Add photos to the chunk
Post by: magic on November 22, 2017, 03:31:48 PM
Works great Alexey
Thx a lot :-)
Title: Re: Add photos to the chunk
Post by: NougierEva on November 23, 2017, 06:46:09 PM
Hi,

I try also to add photos to my chunk but it doesn't work.
The error it's "Empty file list".
But in my folder there are many pictures and their extension is .jpg
So I don't understand what's wrong with my script.
I put my script in attached file.
So, If you have some times, can you help me to fixe my problem.
Thanks,
Eva Ingenior Student
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 23, 2017, 07:11:23 PM
Hello Eva,

Actually in your script the part with the photo_list populating code is missing. It should be in between lines 40 and 41, similar to the example in this thread:
Code: [Select]
# Préciser le dossier contenant les images
path_photos = PhotoScan.app.getExistingDirectory("Specifier le chemin d'accès contenant les images: ")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
Title: Re: Add photos to the chunk
Post by: NougierEva on November 24, 2017, 10:13:41 AM
Thanks a lot, now it works.
I have another question to improve my script. Indeed, I would like to specify by the person who uses the script the coordinate system. In my script, it works, a window appears and asks to precise the coordinate system. Nevertheless, there is no coordinate system to be choosen except to search in a file in the computer. But how to access to all the coordinate system as like as the window when we go to the chunk and reference settings.

I hope it's clear, it's not always easy to explain in english the problem.
I put again in attached file my script reviewed.

Thanks again for your wonderful help,
Have a nice day,
Eva
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 24, 2017, 11:45:50 AM
Hello Eva,

When you are using
Code: [Select]
crs = PhotoScan.app.getCoordinateSystem("Select Coordinate System", doc.chunk.crs)the compact coordinate system selection dialog appears with the recently used systems (the default system will be current coordinate system of the chunk (doc.chunk.crs), but clicking on "More..." option you will be able to open the common coordinate selection dialog, where you can find the required system from the list. Only clicking on Load button will suggest to locate the PRJ file in the file browser.
Title: Re: Add photos to the chunk
Post by: magic on November 24, 2017, 12:45:40 PM
Hi Alexey

Have another problem
Now i want to select enabled cameras (all in my chunk without disabled) and iv tried this

 
Code: [Select]
####
import PhotoScan
chunk = PhotoScan.app.document.chunk
for f in os.listdir(chunk.cameras):
   if re.match(camera.enabled = True, f):
       print f
######


import PhotoScan
chunk = PhotoScan.app/document.chunk
list_of_files = os.listdir(os.getcwd(chunk.cameras))
for each_file in list_of_files:
    if each_file.startswith(camera.enabled == True):
        print (each_file)

####
import PhotoScan
chunk = PhotoScan.app.document.chunk
chunk = doc.chunk
for i in os.listdirrange(len(chunk.cameras)):
    if os.path.isfile(os.path.join(path,i)) and camera.enabled == True in i:
        files.append(i)


No one of code above works , any suggestion Alexey ??
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 24, 2017, 12:50:43 PM
Hello magic,

If you need to select the camera instances that are already added to the active chunk, you do not need to look for some files in the folders:

Code: [Select]
chunk = PhotoScan.app.document.chunk
for camera in chunk.cameras:
    if camera.enabled:
        camera.selected = True
    else:
        camera.selected = False
Title: Re: Add photos to the chunk
Post by: magic on November 24, 2017, 12:57:29 PM
Iv tried it before with small keyboard mistake ^^
works great my friend
thx a lot :-)
Title: Re: Add photos to the chunk
Post by: NougierEva on November 24, 2017, 02:45:44 PM
Thanks a lot for your response,
Now I want to align my photos.
I search on the net, and I find this sentences but it doesn't work and I already don't understand what's wrong with this two sentences.
The error is "An integer is required (got type str)".
This is my first question.
My second question is, how to detect automatically PhotoScan targets and how to import a list of GCP (.tx) and match them with the detection with of course the same name as detected. I let this in comment and I can't try wha't I write because my alignement of photos doesn't work.

Thanks a lot for your reactivity and your help,
Eva
Title: Re: Add photos to the chunk
Post by: magic on November 24, 2017, 06:19:56 PM
re Hi Alexey

One more question 4 today
Now iv added a custom button with some action to my menu and my window works my button do my action , but i cant open my window once closed from my custom menu, when i restart ps my Custom menu is on place then i go to "Selection desactiver" and ---Nothing happens--- , when i add my script manually, will add second "selection desactiver" but its dsnt work ,  tell Alexey what is wrong with my code pls
Code: [Select]
import os
import PhotoScan
from tkinter import*


def center_window(width=300, height=200):
    # hoteur et largeur notre fenetre
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    # calcule positionement notre fenetre sur ecran
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))




####
root = Tk()
center_window(500, 400)
root.title('selection images')


def callback():
    chunk = PhotoScan.app.document.chunk
    for camera in chunk.cameras:
        if camera.enabled:
            camera.selected = True
        else:
            camera.selected = False

but = Button(root, text='selection active', command=callback)

but.pack()


def selec():
    doc = PhotoScan.app.document
    chunk = doc.chunk
PhotoScan.app.addMenuItem("Custom/Selection desactiver", selec)
root.mainloop()


And have a nice weekend Alexey
Any ideas why thats dsnt work ??
Title: Re: Add photos to the chunk
Post by: magic on November 28, 2017, 11:12:19 AM
Hi Alexey

still can't figure out how to make it works, iv been tried few combinations and the script starting with my photoscan but once windows closed cant open it anymore, and it is normal did iv added 4 custom windows and they are opened with photoscan on start all ???
and im using 1.3.4 pro version photoscan

here is my code:
Code: [Select]
import PhotoScan
from tkinter import*

root = Tk()
center_window(500, 400)
root.title('selection images')

def center_window(width=300, height=200):
    # hoteur et largeur notre fenetre
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    # calcule positionement notre fenetre sur ecran
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))

def myfunk():
    doc = PhotoScan.app.document
    chunk = doc.chunk

    def callback():
        chunk = PhotoScan.app.document.chunk
        for camera in chunk.cameras:
            if camera.enabled:
                camera.selected = True
            else:
                camera.selected = False

but = Button(root,bg='yellow',width =20, height =2, bd =2, relief =SOLID, text='selection active', command=callback)

but.pack()
root.mainloop()

PhotoScan.app.addMenuItem("Custom/Give me a name", myfunk)



Any help please Alexey ? I event tried put all my script in to the class and nothing, have not enough skills with python hope so one day that will changed ^-^ .
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 28, 2017, 03:08:30 PM
Now I want to align my photos.
I search on the net, and I find this sentences but it doesn't work and I already don't understand what's wrong with this two sentences.
The error is "An integer is required (got type str)".
This is my first question.
My second question is, how to detect automatically PhotoScan targets and how to import a list of GCP (.tx) and match them with the detection with of course the same name as detected. I let this in comment and I can't try wha't I write because my alignement of photos doesn't work.
Hello Eva,

Probably, you have used outdated scripts as a reference, where string values instead of enum have been used.

See the modified parameters for the image matching:
Code: [Select]
chunk.matchPhotos(accuracy=PhotoScan.HighAccuracy, generic_preselection = True, reference_preselection = False)
chunk.alignPhotos()
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 28, 2017, 03:11:55 PM

still can't figure out how to make it works, iv been tried few combinations and the script starting with my photoscan but once windows closed cant open it anymore, and it is normal did iv added 4 custom windows and they are opened with photoscan on start all ???
and im using 1.3.4 pro version photoscan



Any help please Alexey ? I event tried put all my script in to the class and nothing, have not enough skills with python hope so one day that will changed ^-^ .
Hello magic,

What is written in the Console pane, when you are trying to run the script again?
Title: Re: Add photos to the chunk
Post by: magic on November 28, 2017, 03:34:40 PM
Hello Alexey

iv added 3 scripts
its looks like this:
Custom(and my 3 scripts)
                                          -test
                                          -test1
                                          -selection desactiver

when i choose 1st one send print to console but window stay off, no reaction at click
and 2 others nothing happens in console and window stay off to

but when i restart my photoscan all 3 windows are open, and i cant do any action before i close them
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 28, 2017, 04:24:22 PM
Hello magic,

Maybe some issues with tkinter module installation?

You can use PySide2 module to create custom dialogs, even though it may be not so convenient, as trinker.
Title: Re: Add photos to the chunk
Post by: magic on November 28, 2017, 04:37:31 PM
I will try it Alexey thx
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 28, 2017, 05:01:22 PM
Hello magic,

Check the scripts here that are using custom GUI elements as a reference:
https://github.com/agisoft-llc/photoscan-scripts
Title: Re: Add photos to the chunk
Post by: NougierEva on November 30, 2017, 12:29:00 PM
Thanks for your answer, now it works.
But I have a question about the marker and GCP.
My automatic detection of the PhotoScan markers works but now, I would like to import a file with the coordinate of my GCP and ask the person to select the file because my file will not have necessary the same name each times.
How can I do that ?

Thansk a lot,
Have a nice day,
Eva Nougier
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 30, 2017, 12:43:10 PM
Hello Eva,

Will the order of the columns and delimiter be fixed in the reference file? If so, can you provide as an example a few lines from it and specify, with columns correspond to which values that should be imported?
Title: Re: Add photos to the chunk
Post by: NougierEva on November 30, 2017, 12:59:43 PM
My GCP file contains :
- point name same as PhotoScan (target 2, target 148, etc.)
- coordinate X of the point
- coordinate Y of the point
- coordinate Z of the point
To separate my data, I use a coma.
I already import this file when I did all the work without a Python Script and It works.
I put the file if you want to see.

In my mind, I would like to ask the person to specify the directory of the file (or files).
Then import the file or files.
And try to match the target automatically detected with PhotoScan and their coordinates.

Thanks,
Eva
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on November 30, 2017, 08:28:18 PM
Hello Eva,

After detecting the markers you can add the following lines to your script:
Code: [Select]
path_csv = PhotoScan.app.getOpenFileName("Please specify the path to CSV file:", filter= "CSV file (*.txt *.csv)")
chunk.loadReference(path_csv, format = PhotoScan.ReferenceFormatCSV, columns = "nxyz", delimiter = ",")
It will ask the user for the path to the csv file and then would load the coordinate information to the Reference pane.

I can recommend to ask for the file paths in the beginning of the script, when the user just start them, because it may take a long time to wait for processing to get to the proper stage.
Title: Re: Add photos to the chunk
Post by: NougierEva on December 01, 2017, 02:52:54 PM
Hello,

Thanks for your answer, I fixe my problem thanks to your help. But I have another problem.
I need to precise the coordinate system of my GCP when I import the file as the same way I precise the concatenation of my file (a coma).
I put in attached file my script reviewed.

Really thanks for your help,
I will finish by understand Python Script, it's my goal !! =)
Eva
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on December 01, 2017, 03:20:38 PM
Hello Eva,

Not sure, what exactly do you need to perform after alignment?

If you need to optimize the camera positions, then the following function should be used:
Code: [Select]
optimizeCameras(fit_f=True, fit_cx=True, fit_cy=True, fit_b1=True, fit_b2=True, fit_k1=True, fit_k2=True, fit_k3=True, fit_k4=False, fit_p1=True, fit_p2=True, fit_p3=False, fit_p4=False)You may also need to use chunk.resetRegion() function to reset the position and orientation of the bounding box, that may be off from the camera alignment after referencing the model and optimization.
Title: Re: Add photos to the chunk
Post by: NougierEva on December 02, 2017, 12:06:32 AM
Hi,

Thanks for your answer.
When I import the file with the coordinate of my point, I would like to specify the coordinate system.
My chunk has a coordinate system specify by the user. My file contains points with a coordinate system, the same as the chunk.
I would like when the file is downloaded that the coordinate system of this input file is not the default coordinate system of PhotoScan (WGS84) but the same as the chunk specify by the user.

If I don't specify the coordinate system when I import my file, there are not at their right position and the model comport very high error because of this coordinate system problem.

In my current script, I already arrive to reoptimize the cameras but I don't arrive to precise the coordinate system for the input coordinate points.
This sentence doesn't work and makes error :
chunk.loadReference(path_csv, format = PhotoScan.ReferenceFormatCSV, columns = "nxyz", delimiter = ",", coordinate_system=crs)

I hope I'm more clear in what I want to obtain,

Really thanks for your useful help,
Eva
Title: Re: Add photos to the chunk
Post by: NougierEva on December 05, 2017, 10:50:18 PM
Hi,

I try to resolve my problem of coordinate system of my GCP but it didn't find a solution.
It's the same problem, I have an error message specify that my sentence is wrong.
I would like to specify the coordinate system when  I import the file with the coordinate of my point.
The same thing when I ask the user to specify the coordinate system of the chunk.

My current script has not really improved because I'm stuck with this problem of coordinate.
So, my current expression is wrong but I can't find how to modify this :
chunk.loadReference(path_csv, format = PhotoScan.ReferenceFormatCSV, columns = "nxyz", delimiter = ",", coordinate_system=crs)

Thanks for your help,
I'm a lit bit lost !

Eva
Title: Re: Add photos to the chunk
Post by: magic on December 18, 2017, 05:25:39 PM
Hi Alexey
Iv got some small problem again , now I try to load the cameras to my chunk and the cameras are in main directory and I have sub-folders inside it is possible to get the cameras and load them to new cameras group for each sub-folder ??
Iv tried thats but dsnt work as i would to

doc = PhotoScan.app.document
chunk = doc.addChunk()
chunk.label = "New Chunk"

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
           photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")

group = chunk.addCameraGroup()
for img in image_list:
    camera = chunk.cameras[0]
    group = chunk.addCameraGroup()
    camera.group = group
    group.type = PhotoScan.CameraGroup.Station

Any suggestion Alexey ??
Title: Re: Add photos to the chunk
Post by: magic on December 19, 2017, 10:49:40 AM
Hi Alexey
Iv got some small problem again , now I try to load the cameras to my chunk and the cameras are in main directory and I have sub-folders inside it is possible to get the cameras and load them to new cameras group for each sub-folder ??
Iv tried thats but dsnt work as i would to

Code: [Select]
doc = PhotoScan.app.document
chunk = doc.addChunk()
new_group = chunk.addCameraGroup()

# Ajout de photos -add photos 1st chunk
path_photos = PhotoScan.app.getExistingDirectory("main folder:")
image_list = os.listdir(path_photos)
photo_list = list()
for photo in image_list:
    if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
        photo_list.append("/".join([path_photos, photo]))
chunk.addPhotos(photo_list)
print("- Photos ajoutées")

for camera in list(chunk.cameras):
camera.group = new_group
Its better but still dsnt work
Any suggestion Alexey ??
Title: Re: Add photos to the chunk
Post by: magic on December 19, 2017, 02:06:34 PM
Anybody here ??
Title: Re: Add photos to the chunk
Post by: Alexey Pasumansky on December 20, 2017, 05:45:47 PM
Hello magic,

Please try this code to load the images from the sub-directories of the user-defined master folder to separate camera groups in the same chunk:
Code: [Select]
import PhotoScan, os

doc = PhotoScan.app.document
chunk = doc.addChunk()

path_master = PhotoScan.app.getExistingDirectory("Main folder:")
sub_folders = os.listdir(path_master)
for folder in sub_folders:
folder = os.path.join(path_master, folder)
if not os.path.isdir(folder):
continue

image_list = os.listdir(folder)
photo_list = list()
new_group = chunk.addCameraGroup()
new_group.label = os.path.basename(folder)
for photo in image_list:
if photo.rsplit(".",1)[1].lower() in  ["jpg", "jpeg", "tif", "tiff"]:
photo_list.append(os.path.join(folder, photo))
chunk.addPhotos(photo_list)
for camera in chunk.cameras:
if not camera.group:
camera.group = new_group