def make_project(project_dir, photos_dir): 'Make a new project and add the photos from the photos_dir to it.' log("Making project " + project_dir) doc = PhotoScan.Document( ) # Operate on a new document for batch proecssing #doc = PhotoScan.app.document # Use the current open document in PhotoScan # Add the photos to a chunk chunk = doc.addChunk() photos_dir = os.path.join(project_dir, photos_dir) photos = os.listdir(photos_dir) photos = [os.path.join(photos_dir, p) for p in photos] log("Found {} photos in {}".format(len(photos), photos_dir)) if not chunk.addPhotos(photos): log("ERROR: Failed to add photos: " + str(photos)) # Save the new project project_name = make_project_filename(project_dir, "psz") log("Saving: " + project_name) if not doc.save(project_name): log("ERROR: Failed to save project: " + project_name) return doc
def make_project(project_dir, chunk_dirs): 'Make a new project and a chunk for each directory.' log("Making project " + project_dir) # Create new doc doc = PhotoScan.Document( ) # Operate on a new document for batch proecssing #doc = PhotoScan.app.document # Use the current open document in PhotoScan # Go through each chunk directory for chunk_dir in chunk_dirs: chunk = doc.addChunk() # Create the chunk chunk.label = os.path.basename(chunk_dir) photos = os.listdir(chunk_dir) # Get the photos filenames photos = [os.path.join(chunk_dir, p) for p in photos] # Make them into a full path log("Found {} photos in {}".format(len(photos), chunk_dir)) if not chunk.addPhotos(photos): log("ERROR: Failed to add photos: " + str(photos)) # Save the new project project_name = make_project_filename(project_dir, "psz") log("Saving: " + project_name) if not doc.save(project_name): log("ERROR: Failed to save project: " + project_name) return doc
def open_project(project_dir): log("Opening project " + project_dir) project_name = make_project_filename(project_dir, "psz") doc = PhotoScan.Document() if not doc.open(project_name): log("ERROR: Cold not open document: " + project_name) return doc
def create_new_project(self): if not os.path.exists(path=self.project_file_name + self.PROJECT_TYPE): new_project = PhotoScan.Document() chunk = new_project.addChunk() new_project.save( path=self.project_file_name + self.PROJECT_TYPE, chunks=[chunk] )
def main(): #prompting for path to photos path_photos = PhotoScan.app.getExistingDirectory("Specify INPUT photo folder(containing all metashape files):") path_export = PhotoScan.app.getExistingDirectory("Specify EXPORT folder:") #processing parameters accuracy = PhotoScan.Accuracy.HighAccuracy #align photos accuracy preselection = PhotoScan.Preselection.GenericPreselection keypoints = 40000 #align photos key point limit tiepoints = 10000 #align photos tie point limit threshold=0.5 fold_list = os.listdir(path_photos) for folder in fold_list: #print("folder name is : "+folder) #loading images folderPath = path_photos + "\\" + folder image_list = os.listdir(folderPath) photo_list = list() for photo in image_list: if ("jpg" or "jpeg" or "JPG" or "JPEG") in photo.lower(): photo_list.append(os.path.join(folderPath,photo)) doc = PhotoScan.Document() doc.save(path_export+"\\"+folder+".psx") chunk=doc.addChunk() chunk.addPhotos(photo_list) #align photos chunk.matchPhotos(accuracy = accuracy, preselection = preselection, filter_mask = False, keypoint_limit = keypoints, tiepoint_limit = tiepoints) chunk.alignCameras() #Removing points outside bounding box chunk = doc.chunks[-1] R = chunk.region.rot #Bounding box rotation matrix C = chunk.region.center #Bounding box center vertor size = chunk.region.size if not (chunk.point_cloud and chunk.enabled): continue elif not len(chunk.point_cloud.points): continue for point in chunk.point_cloud.points: if point.valid: v = point.coord v.size = 3 v_c = v - C v_r = R.t() * v_c if abs(v_r.x) > abs(size.x / 2.): point.valid = False elif abs(v_r.y) > abs(size.y / 2.): point.valid = False elif abs(v_r.z) > abs(size.z / 2.): point.valid = False else: continue #Points outside the region were removed. #Read reprojection error and delete any 0.5 or greater f = PhotoScan.PointCloud.Filter() f.init(chunk, criterion=PhotoScan.PointCloud.Filter.ReprojectionError) f.removePoints(threshold) doc.save()
# How to launch # ./photoscan-pro/photoscan.sh -r "path_to_script.py" import PhotoScan import os doc = PhotoScan.Document() path = "/home/ben/Downloads/photoscan/monument/3_views/" #path to the image folder # chunk = PhotoScan.Chunk() chunk = doc.addChunk() chunk.label = "New Chunk" # doc.chunks.add(chunk) photos_list = os.listdir(path) tofList = [] for tof in photos_list: tofList.append(path + "/" + tof) print(tofList) # for photo_name in tofList: #adding all files from the folder chunk.addPhotos(tofList) #Align Photos chunk.matchPhotos(accuracy=PhotoScan.HighAccuracy) # chunk.matchPhotos(accuracy = "high", preselection="disabled", filter_mask=False, point_limit=40000) chunk.alignCameras() # chunk.alignPhotos()
def process(images_path, output_path, reference_path, model_name): # Font settings os.environ['QT_QPA_FONTDIR'] = '/usr/share/fonts/truetype/dejavu/' # Below code was to enable all available GPUs, was throwing an error. #PhotoScan.app.gpu_mask = 2 ** len(PhotoScan.app.enumGPUDevices()) - 1 #setting GPU mask PhotoScan.app.gpu_mask = 3 # gpu_mask is a bitmask. 3 in binary = 11 so only two GPUs are used. if PhotoScan.app.gpu_mask: PhotoScan.app.cpu_enable = False else: PhotoScan.app.cpu_enable = True ### Processing parameters accuracy = PhotoScan.Accuracy.HighAccuracy #align photos accuracy reference_preselection = False generic_preselection = True keypoints = 40000 # Align photos key point limit tiepoints = 4000 # Align photos tie point limit source = PhotoScan.DataSource.DenseCloudData # Build mesh/DEM source surface = PhotoScan.SurfaceType.Arbitrary # Build mesh surface type quality = PhotoScan.Quality.MediumQuality # Build dense cloud quality filtering = PhotoScan.FilterMode.AggressiveFiltering # Depth filtering interpolation = PhotoScan.Interpolation.EnabledInterpolation # Build mesh interpolation mosaic_blending = PhotoScan.BlendingMode.MosaicBlending # Blending mode average_blending = PhotoScan.BlendingMode.AverageBlending disabled_blending = PhotoScan.BlendingMode.DisabledBlending face_num = PhotoScan.FaceCount.HighFaceCount # Build mesh polygon count mapping = PhotoScan.MappingMode.GenericMapping #Build texture mapping atlas_size = 4096 TYPES = ["jpg", "jpeg", "tif", "tiff", "png"] # Load images into master list of fore and aft. list_photos_master = load_images(TYPES, images_path) # Create PhotoScan document project_file = os.path.join(output_path, "Model.psx") doc = PhotoScan.Document() doc.save(project_file) chunk = doc.addChunk() chunk.label = model_name print("Saving PhotoScan project to: ", project_file) print("Chunk label: ", str(chunk.label)) # Add Images to Chunk chunk.addPhotos(list_photos_master) # Load ref file. chunk.loadReference(path=reference_path, format=PhotoScan.ReferenceFormat.ReferenceFormatCSV, columns='zanxy', delimiter=',') # Set coordinate system for lat lon values. chunk.crs = PhotoScan.CoordinateSystem("EPSG::4326") # TODO Load calibration parameters from file # Create Sensor definitions sensor_fore = chunk.addSensor() sensor_fore.label = "Fore Sensor" sensor_fore.type = PhotoScan.Sensor.Type.Frame sensor_fore.width = chunk.cameras[-1].sensor.width sensor_fore.height = chunk.cameras[-1].sensor.height sensor_fore.pixel_size = [0.00345, 0.00345] sensor_fore.focal_length = 6.7 # Focal length is 10.4mm, 14.6mm effective length in water. sensor_fore.antenna.location_ref = PhotoScan.Vector([0.38, 0, 0.25]) sensor_aft = chunk.addSensor() sensor_aft.label = "Aft Sensor" sensor_aft.type = PhotoScan.Sensor.Type.Frame sensor_aft.width = chunk.cameras[-1].sensor.width sensor_aft.height = chunk.cameras[-1].sensor.height sensor_aft.pixel_size = [0.00345, 0.00345] sensor_aft.focal_length = 6.7 sensor_aft.antenna.location_ref = PhotoScan.Vector([0.53, 0, 0.25]) for camera in chunk.cameras: if "F" in camera.label: camera.sensor = sensor_fore print("Added ", camera.label, "to fore group") elif "A" in camera.label: camera.sensor = sensor_aft print("Added ", camera.label, "to aft group") else: print("No sensor defined for ", camera.label) # Add scalebars between stereo images # This is the baseline between two cameras. # Iver3 system is 6" baseline, 0.1524 meters. index = 0 while (True): scalebar = chunk.addScalebar(chunk.cameras[index], chunk.cameras[index + 1]) scalebar.reference.distance = 0.1524 index += 2 if index >= len(chunk.cameras): break ### Estimate image quality chunk.estimateImageQuality(chunk.cameras) badImages = 0 #for camera in chunk.cameras: # if float(camera.photo.meta["Image/Quality"]) < 0.5: # camera.enabled = False # badImages+=1 print("Removed ", badImages, " from chunk") ### Align photos chunk.matchPhotos(accuracy=accuracy, generic_preselection=generic_preselection, reference_preselection=reference_preselection, filter_mask=False, keypoint_limit=keypoints, tiepoint_limit=tiepoints, progress=progress_print) chunk.alignCameras() chunk.optimizeCameras() chunk.resetRegion() doc.read_only = False doc.save() ###building dense cloud chunk.buildDepthMaps(quality=quality, filter=filtering, progress=progress_print) chunk.buildDenseCloud(point_colors=True, progress=progress_print) doc.save() ###building mesh chunk.buildModel(surface=surface, source=source, interpolation=interpolation, face_count=face_num, progress=progress_print) doc.save() ###build texture chunk.buildUV(mapping=mapping, count=1, progress=progress_print) chunk.buildTexture(blending=mosaic_blending, size=atlas_size, progress=progress_print) doc.save() ###export model chunk.exportModel(path=os.path.join(output_path, chunk.label + ".obj"), binary=False, texture_format=PhotoScan.ImageFormatJPEG, texture=True, normals=False, colors=False, cameras=False, format=PhotoScan.ModelFormatOBJ) ### Export GeoTiff file chunk.buildDem(source=source, interpolation=interpolation, projection=chunk.crs, progress=progress_print) chunk.exportDem( path=os.path.join(output_path, chunk.label + '_DEM.jpeg'), image_format=PhotoScan.ImageFormat.ImageFormatJPEG, raster_transform=PhotoScan.RasterTransformType.RasterTransformPalette, projection=chunk.crs, nodata=-32767, write_kml=True, write_world=True, write_scheme=True, tiff_big=True) # Export orthomosaic chunk.buildOrthomosaic(surface=PhotoScan.DataSource.ElevationData, blending=mosaic_blending, fill_holes=True) chunk.exportOrthomosaic(path=os.path.join( output_path, chunk.label + '_' + str(mosaic_blending) + '_orthomosaic.tif'), projection=chunk.crs) chunk.buildOrthomosaic(surface=PhotoScan.DataSource.ElevationData, blending=average_blending, fill_holes=True) chunk.exportOrthomosaic(path=os.path.join( output_path, chunk.label + '_' + str(average_blending) + '_orthomosaic.tif'), projection=chunk.crs) chunk.buildOrthomosaic(surface=PhotoScan.DataSource.ElevationData, blending=disabled_blending, fill_holes=True) chunk.exportOrthomosaic(path=os.path.join( output_path, chunk.label + '_' + str(disabled_blending) + '_orthomosaic.tif'), projection=chunk.crs) ### Export camera poses export_camera_pose( chunk, os.path.join(output_path, chunk.label + '_camera_pose.csv')) ### Generate report chunk.exportReport(os.path.join(output_path, chunk.label + '_report.pdf')) print("Processed " + chunk.label) return True
def process(path): PhotoScan.app.gpu_mask = 2 ** len(PhotoScan.app.enumGPUDevices()) - 1 #setting GPU mask if PhotoScan.app.gpu_mask: PhotoScan.app.cpu_enable = False else: PhotoScan.app.cpu_enable = True ### processing parameters accuracy = PhotoScan.Accuracy.HighAccuracy #align photos accuracy reference_preselection = False generic_preselection = True keypoints = 40000 #align photos key point limit tiepoints = 4000 #align photos tie point limit source = PhotoScan.DataSource.DenseCloudData #build mesh/DEM source surface = PhotoScan.SurfaceType.Arbitrary #build mesh surface type quality = PhotoScan.Quality.MediumQuality #build dense cloud quality filtering = PhotoScan.FilterMode.AggressiveFiltering #depth filtering interpolation = PhotoScan.Interpolation.EnabledInterpolation #build mesh interpolation blending = PhotoScan.BlendingMode.MosaicBlending #blending mode face_num = PhotoScan.FaceCount.HighFaceCount #build mesh polygon count mapping = PhotoScan.MappingMode.GenericMapping #build texture mapping atlas_size = 4096 TYPES = ["jpg", "jpeg", "tif", "tiff"] ###end of processing parameters definition print("Processing " + path) list_files = os.listdir(path) list_photos = list() for entry in list_files: #finding image files file = path + "/" + entry if os.path.isfile(file): if file[-3:].lower() in TYPES: list_photos.append(file) if not(len(list_photos)): print("No images in " + path) return False doc = PhotoScan.Document() doc.save(path + "/" + path.rsplit("/", 1)[1] + ".psx") chunk = doc.addChunk() chunk.label = path.rsplit("/", 1)[1] ###align photos chunk.addPhotos(list_photos) chunk.matchPhotos(accuracy = accuracy, generic_preselection = generic_preselection, reference_preselection = reference_preselection, filter_mask = False, keypoint_limit = keypoints, tiepoint_limit = tiepoints) chunk.alignCameras() chunk.optimizeCameras() chunk.resetRegion() doc.save() ###building dense cloud chunk.buildDepthMaps(quality = quality, filter = filtering) chunk.buildDenseCloud(point_colors = True, keep_depth = False) doc.save() ###building mesh chunk.buildModel(surface = surface, source = source, interpolation = interpolation, face_count = face_num) doc.save() ###build texture chunk.buildUV(mapping = mapping, count = 1) chunk.buildTexture(blending = blending, size = atlas_size) doc.save() ###export model chunk. exportModel(path = path + "/" + chunk.label + ".obj", binary=False, texture_format=ImageFormatJPEG, texture=True, normals=False, colors=False, cameras=False, format = PhotoScan.ModelFormatOBJ) print("Processed " + chunk.label) return True
def generate3D(filePath): fullPathPhotoDirectoryName = filePath # Define: AlignPhotosAccuracy ["high", "medium", "low"] #change me print("\n**enum gpu devices", PhotoScan.app.enumGPUDevices()) print("\n**gpu mask ", PhotoScan.app.gpu_mask) TireAuditDataRoot = os.path.dirname( os.path.dirname(fullPathPhotoDirectoryName)) + "\\" #1 PhotoScanInputGCPFileTireAuditMarkers=generate_3DSettings.photoScanGCPFile #1 PhotoScanInputGCPFileAgisoftMarkers=TireAuditDataRoot+"gcp_agisoft.csv" #1 PhotoScanInputGCPFileAgisoftMarkers=TireAuditDataRoot+"foo4.txt" PhotoScanInputCalibFile = generate_3DSettings.photoScanCalibrationFile #fdebug.write("\n ********************* TireAuditDataRoot PhotoScanInputCalibFile PhotoScanInputGCPFileAgisoftMarkers PhotoScanInputGCPFileAgisoftMarkers PhotoScanInputCalibFile\n ",TireAuditDataRoot , PhotoScanInputCalibFile , PhotoScanInputGCPFileAgisoftMarkers, PhotoScanInputGCPFileAgisoftMarkers ,PhotoScanInputCalibFile) PhotoScanPlyFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanPlyName PhotoScanLogFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanLogName PhotoScanDebugFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanDebugName PhotoScanProjectFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanProjectName PhotoScanReprojectionErrorsFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanReprojectionErrorsName #PhotoScanMarkerFile = fullPathPhotoDirectoryName+"\\"+generate_codesSettings.markerInformationPixelToCode #fdebug.write("\n*********** Checking for %s \n", PhotoScanProjectFile) # if path already has a psz file in exit then go onto nex directory if os.path.exists(PhotoScanProjectFile): #fdebug.write("\n*********** already proceessed %s \n", PhotoScanProjectFile) exit fdebug = open(PhotoScanDebugFile, 'w') flog = open(PhotoScanLogFile, 'w') start = time.time() #####pattern = 'IMG_*[02468].JPG' pattern = 'IMG_*' #print 'Pattern :', pattern print("abc") #files = os.listdir('.') files = os.listdir(fullPathPhotoDirectoryName) photoList = [] for filename in fnmatch.filter(files, pattern): #print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern)) ) #item = fullPathPhotoDirectoryName+"\\"+filename item = os.path.join(fullPathPhotoDirectoryName, filename) photoList.append(item) print("\n777 Photolist is ", photoList) doc = PhotoScan.Document() chunk = doc.addChunk() chunk.crs = PhotoScan.CoordinateSystem( 'LOCAL_CS["Local Coordinates",LOCAL_DATUM["Local Datum",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]]]' ) chunk.label = "New ChunkB" cameraDictionary = {} user_calib = PhotoScan.Calibration() success = user_calib.load(PhotoScanInputCalibFile) print("\n success loading calib file ", success) sensor = chunk.addSensor( ) #creating camera calibration group for the loaded image sensor.label = "Calibration Group 1" sensor.type = PhotoScan.Sensor.Type.Frame #sensor.width = camera.photo.image().width #sensor.height = camera.photo.image().height sensor.width = 5312 sensor.height = 2988 sensor.fixed = True sensor.user_calib = user_calib #sensor.width = 3264 #1 chunk.marker_projection_accuracy=0.0002 for i, filepath in enumerate(photoList): fdebug.write("\nxxxxxxxx filepath" + " " + filepath) camera = chunk.addCamera() camera.sensor = sensor pos = filepath.find("IMG") img = filepath[pos:] #cameraDictionary[img]=i cameraDictionary[img] = camera.key camera.open(filepath) #camera.open("c:\\Projects\\123DCatch\\Tires_25982510_B_Samsung6ChoppedExampleForTesting\\A\\IMG_14.JPG") camera.label = img #fdebug.write("\n filepath key", filepath, camera.key,camera.photo.image().width,camera.photo.image().height) fdebug.write("\n filepath key" + " " + filepath + " " + str(camera.key) + " " + camera.photo.path) fdebug.write("\n^^^^^^^^^^ Camera Dictionary" + " " + str(cameraDictionary)) fdebug.write("\n PhotoList &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n" + " " + str(photoList)) fdebug.write("hello") templateName = fullPathPhotoDirectoryName + "\\" + "M{filename}.JPG" #templateName=fullPathPhotoDirectoryName+ "\\" + "M{filename}.JPG" #successMask=chunk.importMasks(path=templateName,method='file',tolerance=10) successMask = chunk.importMasks( path=templateName, source=PhotoScan.MaskSourceFile, operation=PhotoScan.MaskOperationReplacement, tolerance=10, cameras=chunk.cameras) print( "\n***********************&&&&&&&&&&&&&&&&& successMask ************", successMask) #ALIGN PHOTOS fdebug.write("---Aligning photos ...") fdebug.write("Accuracy: " + generate_3DSettings.matchAccuracy) fdebug.write("\nBefore Matching **** \n") if (generate_3DSettings.matchAccuracy == "Low"): accuracyMatch = PhotoScan.Accuracy.LowAccuracy elif (generate_3DSettings.matchAccuracy == "High"): accuracyMatch = PhotoScan.Accuracy.HighAccuracy else: accuracyMatch = PhotoScan.Accuracy.MediumAccuracy if (generate_3DSettings.modelAccuracy == "Ultra"): accuracyModel = PhotoScan.Quality.UltraQuality elif (generate_3DSettings.modelAccuracy == "High"): accuracyModel = PhotoScan.Quality.HighQuality elif (generate_3DSettings.modelAccuracy == "Low"): accuracyModel = PhotoScan.Quality.LowQuality elif (generate_3DSettings.modelAccuracy == "Lowest"): accuracyModel = PhotoScan.Quality.LowestQuality else: accuracyModel = PhotoScan.Quality.MediumQuality chunk.matchPhotos(accuracy=accuracyMatch, preselection=PhotoScan.Preselection.GenericPreselection, filter_mask=True) fdebug.write("\nBefore Align **** \n") chunk.alignCameras() fdebug.write("\nBefore Optimize **** \n") chunk.optimizeCameras() fdebug.write("\nBefore Build Dense **** \n") chunk.buildDenseCloud(quality=accuracyModel) fdebug.write("\nBefore Build Model **** \n") #chunk.buildModel(surface= PhotoScan.SurfaceType.Arbitrary, interpolation=PhotoScan.Interpolation.EnabledInterpolation , face_count=generate_3DSettings.faceCount) #chunk.buildModel(surface= PhotoScan.SurfaceType.Arbitrary, interpolation=PhotoScan.Interpolation.EnabledInterpolation , face_count=300000) fdebug.write("\nBefore Build Texture **** \n") mapping = PhotoScan.MappingMode.GenericMapping #build texture mapping chunk.buildUV(mapping=mapping, count=1) chunk.buildTexture() #chunk.exportModel(path=PhotoScanPlyFile, format = 'ply', texture_format='jpg') chunk.exportModel(PhotoScanPlyFile, format=PhotoScan.ModelFormat.ModelFormatPLY, texture_format=PhotoScan.ImageFormat.ImageFormatJPEG) #chunk.exportModel(path_export + "\\model.obj", format = "obj", texture_format='PhotoScan.ImageFormat.ImageFormatJPEG) PhotoScan.app.update() #save ground control information a chunk.saveReference(PhotoScanReprojectionErrorsFile, PhotoScan.ReferenceFormat.ReferenceFormatCSV) # # if not(chunk.saveReference(PhotoScanReprojectionErrorsFile, PhotoScan.ReferenceFormat.ReferenceFormatCSV )): # app.messageBox("Saving GCP info failed!") # # SAVE PROJECT fdebug.write("---Saving project...") fdebug.write("File: " + PhotoScanProjectFile) doc.save(PhotoScanProjectFile) doc.chunks.remove(chunk) end = time.time() fdebug.close() flog.write('\nelapsed time =' + str(end - start)) # python will convert \n to os.linesep flog.close() return
def generate3D(filePath): fullPathPhotoDirectoryName = filePath # Define: AlignPhotosAccuracy ["high", "medium", "low"] TireAuditDataRoot = os.path.dirname( os.path.dirname(fullPathPhotoDirectoryName)) + "\\" PhotoScanInputGCPFileTireAuditMarkers = generate_3DSettings.photoScanGCPFile PhotoScanInputGCPFileAgisoftMarkers = TireAuditDataRoot + "gcp_agisoft.csv" PhotoScanInputGCPFileAgisoftMarkers = TireAuditDataRoot + "foo4.txt" PhotoScanInputCalibFile = generate_3DSettings.photoScanCalibrationFile #fdebug.write("\n ********************* TireAuditDataRoot PhotoScanInputCalibFile PhotoScanInputGCPFileAgisoftMarkers PhotoScanInputGCPFileAgisoftMarkers PhotoScanInputCalibFile\n ",TireAuditDataRoot , PhotoScanInputCalibFile , PhotoScanInputGCPFileAgisoftMarkers, PhotoScanInputGCPFileAgisoftMarkers ,PhotoScanInputCalibFile) PhotoScanPlyFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanPlyName PhotoScanLogFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanLogName PhotoScanDebugFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanDebugName PhotoScanProjectFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanProjectName PhotoScanReprojectionErrorsFile = fullPathPhotoDirectoryName + "\\" + generate_3DSettings.photoScanReprojectionErrorsName PhotoScanMarkerFile = fullPathPhotoDirectoryName + "\\" + generate_codesSettings.markerInformationPixelToCode #fdebug.write("\n*********** Checking for %s \n", PhotoScanProjectFile) # if path already has a psz file in exit then go onto nex directory if os.path.exists(PhotoScanProjectFile): #fdebug.write("\n*********** already proceessed %s \n", PhotoScanProjectFile) exit fdebug = open(PhotoScanDebugFile, 'w') flog = open(PhotoScanLogFile, 'w') start = time.time() print("\n**enum gpu devices", PhotoScan.app.enumGPUDevices()) print("\n**gpu mask ", PhotoScan.app.gpu_mask) enumDev = PhotoScan.app.enumGPUDevices() gpu_mask = PhotoScan.app.gpu_mask fdebug.write("\n**enum gpu devices " + str(PhotoScan.app.enumGPUDevices())) fdebug.write("\n**gpu mask " + str(PhotoScan.app.gpu_mask)) #change me #####pattern = 'IMG_*[02468].JPG' pattern = 'IMG_*' #print 'Pattern :', pattern print("abc") #files = os.listdir('.') files = os.listdir(fullPathPhotoDirectoryName) photoList = [] for filename in fnmatch.filter(files, pattern): #print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern)) ) #item = fullPathPhotoDirectoryName+"\\"+filename item = os.path.join(fullPathPhotoDirectoryName, filename) photoList.append(item) print("\n777 Photolist is ", photoList) doc = PhotoScan.Document() chunk = doc.addChunk() chunk.crs = PhotoScan.CoordinateSystem( 'LOCAL_CS["Local Coordinates",LOCAL_DATUM["Local Datum",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]]]' ) #successLoad=chunk.loadReference("c:\\temp\\pgcp.csv","csv") #successLoad=chunk.loadReference("c:\\temp\\foo1.csv","csv") #successLoad=chunk.loadReference("c:\\temp\\dtest.csv","csv") #print ("\n ############# Success Load is ", successLoad) #chunk.updateTransform() chunk.label = "New ChunkB" cameraDictionary = {} user_calib = PhotoScan.Calibration() success = user_calib.load(PhotoScanInputCalibFile) print("\n success loading calib file ", success) sensor = chunk.addSensor( ) #creating camera calibration group for the loaded image sensor.label = "Calibration Group 1" sensor.type = PhotoScan.Sensor.Type.Frame #sensor.width = camera.photo.image().width #sensor.height = camera.photo.image().height sensor.width = 5312 sensor.height = 2988 sensor.fixed = True sensor.user_calib = user_calib #sensor.width = 3264 #sensor.height = 2448 #sensor.calibration.cx=1.61822175e+03 #sensor.calibration.cy=1.26702669e+03 #sensor.calibration.fx=3.08768833e+03 #sensor.calibration.fy=3.08786068e+03 #sensor.calibration.k1=0.23148765 #sensor.calibration.k2=0.51836559 #sensor.calibration.k3=-0.48297284 # sensor.calibration.fx = 3.99411182e+03 # sensor.calibration.fy = 3.99418122e+03 # sensor.calibration.cx = 2.68713926e+03 # sensor.calibration.cy = 1.51055154e+03 # sensor.calibration.k1= 0.24503953 # sensor.calibration.k2 = -0.80636859 # sensor.calibration.k3 = 0.77637451 # sensor.user_calib.fx = 3.99411182e+03 # sensor.user_calib.fy = 3.99418122e+03 # sensor.user_calib.cx = 2.68713926e+03 # sensor.user_calib.cy = 1.51055154e+03 # sensor.user_calib.k1= 0.24503953 # sensor.user_calib.k2 = -0.80636859 # sensor.user_calib.k3 = 0.77637451 # sensor.user_calib = True # sensor.calibration.fx = 4.05913e+03 # sensor.calibration.fy = 4.06049e+03 # sensor.calibration.cx = 2.68463e+03 # sensor.calibration.cy = 1.52241e+03 # sensor.calibration.k1= 0.273712 # sensor.calibration.k2 = -1.03971 # sensor.calibration.k3 = 1.05705 chunk.marker_projection_accuracy = 0.0002 for i, filepath in enumerate(photoList): fdebug.write("\nxxxxxxxx filepath" + " " + filepath) camera = chunk.addCamera() camera.sensor = sensor pos = filepath.find("IMG") img = filepath[pos:] #cameraDictionary[img]=i cameraDictionary[img] = camera.key camera.open(filepath) #camera.open("c:\\Projects\\123DCatch\\Tires_25982510_B_Samsung6ChoppedExampleForTesting\\A\\IMG_14.JPG") camera.label = img #fdebug.write("\n filepath key", filepath, camera.key,camera.photo.image().width,camera.photo.image().height) fdebug.write("\n filepath key" + " " + filepath + " " + str(camera.key) + " " + camera.photo.path) fdebug.write("\n^^^^^^^^^^ Camera Dictionary" + " " + str(cameraDictionary)) fdebug.write("\n PhotoList &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n" + " " + str(photoList)) fdebug.write("hello") if (os.path.isfile(PhotoScanMarkerFile)): automaticMarkers = False else: automaticMarkers = True fdebug.write("\n ^^^^^^^^^^^^^^^^^ automatic markers is \n " + str(automaticMarkers) + "\n") if (automaticMarkers): chunk.detectMarkers(PhotoScan.TargetType.CircularTarget20bit, 44) print( "\n ^^^^^^^^^^^^^^^^^ loading automatic ground contreol information\n", PhotoScanInputGCPFileAgisoftMarkers, "\n") successLoad = chunk.loadReference(PhotoScanInputGCPFileAgisoftMarkers, "csv") fdebug.write("\n succes load is" + " " + str(successLoad)) else: markerNamePosList = [] processTAMarkers(PhotoScanMarkerFile, markerNamePosList, chunk, cameraDictionary, fdebug) fdebug.write( "\n ^^^^^^^^^^^^^^^^^ loading ground contreol information\n" + " " + PhotoScanInputGCPFileTireAuditMarkers + "\n") #successLoad=chunk.loadReference("c:\\temp\\gcp_25982510.csv","csv") successLoad = chunk.loadReference( PhotoScanInputGCPFileTireAuditMarkers) # load in ground control information # load in masks templateName = fullPathPhotoDirectoryName + "\\" + "M{filename}.JPG" #templateName=fullPathPhotoDirectoryName+ "\\" + "M{filename}.JPG" #successMask=chunk.importMasks(path=templateName,method='file',tolerance=10) #ALIGN PHOTOS fdebug.write("---Aligning photos ...") fdebug.write("Accuracy: " + generate_3DSettings.matchAccuracy) fdebug.write("\nBefore Matching **** \n") if (generate_3DSettings.matchAccuracy == "Low"): accuracyMatch = PhotoScan.Accuracy.LowAccuracy elif (generate_3DSettings.matchAccuracy == "High"): accuracyMatch = PhotoScan.Accuracy.HighAccuracy else: accuracyMatch = PhotoScan.Accuracy.MediumAccuracy if (generate_3DSettings.modelAccuracy == "Ultra"): accuracyModel = PhotoScan.Quality.UltraQuality elif (generate_3DSettings.modelAccuracy == "High"): accuracyModel = PhotoScan.Quality.HighQuality elif (generate_3DSettings.modelAccuracy == "Low"): accuracyModel = PhotoScan.Quality.LowQuality elif (generate_3DSettings.modelAccuracy == "Lowest"): accuracyModel = PhotoScan.Quality.LowestQuality else: accuracyModel = PhotoScan.Quality.MediumQuality chunk.matchPhotos(accuracy=accuracyMatch, preselection=PhotoScan.Preselection.GenericPreselection) fdebug.write("\nBefore Align **** \n") chunk.alignCameras() fdebug.write("\nBefore Optimize **** \n") chunk.optimizeCameras() fdebug.write("\nBefore Build Dense **** \n") chunk.buildDenseCloud(quality=accuracyModel) fdebug.write("\nBefore Build Model **** \n") chunk.buildModel( surface=PhotoScan.SurfaceType.Arbitrary, interpolation=PhotoScan.Interpolation.EnabledInterpolation, face_count=generate_3DSettings.faceCount) fdebug.write("\nBefore Build Texture **** \n") mapping = PhotoScan.MappingMode.GenericMapping #build texture mapping chunk.buildUV(mapping=mapping, count=1) chunk.buildTexture() #chunk.exportModel(path=PhotoScanPlyFile, format = 'ply', texture_format='jpg') chunk.exportModel(PhotoScanPlyFile, format=PhotoScan.ModelFormat.ModelFormatPLY, texture_format=PhotoScan.ImageFormat.ImageFormatJPEG) #chunk.exportModel(path_export + "\\model.obj", format = "obj", texture_format='PhotoScan.ImageFormat.ImageFormatJPEG) PhotoScan.app.update() #save ground control information a chunk.saveReference(PhotoScanReprojectionErrorsFile, PhotoScan.ReferenceFormat.ReferenceFormatCSV) # # if not(chunk.saveReference(PhotoScanReprojectionErrorsFile, PhotoScan.ReferenceFormat.ReferenceFormatCSV )): # app.messageBox("Saving GCP info failed!") # # SAVE PROJECT fdebug.write("---Saving project...") fdebug.write("File: " + PhotoScanProjectFile) doc.save(PhotoScanProjectFile) doc.chunks.remove(chunk) end = time.time() fdebug.close() flog.write('\nelapsed time =' + str(end - start)) # python will convert \n to os.linesep flog.close() return