Forum

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - Emanuele1234

Pages: [1]
1
Python and Java API / Speed up my Metashape process, any solution?
« on: July 19, 2022, 07:04:50 PM »
Hi everyone!

I'm working with metashape and python, and I'm trying to speed up a little my script, because I have to process 1 milion point.
Considering the impossibility to multiprocess or parallelize my process inside Metashape, where I extract 2d coordinates from the best camera for eny 3d coordinate. I was thinking to extract in some kind of way all the parameters of any camera inside the program to use these to make the projection of eny single 3d point out from the metashape program, and maybe speed up a little everything. what do you think about this possibility? Do you have any Script advice to help me?

Thnak you in advance for your time.
Best regards
Emanuele

2
Dear everyone,

I have a little question about how Python and Metashape works.
I have a problem, because I have to speed up a script which extract coordinates for any selected point in Metashape, but it needs like 27 days to run across 1 milion points.
For this reason I was wondering if you know a way to multiprocess everything and speed up a little the process.
I have already splitted  my dataframe in several parts, to call it in different functions, and I tried with asyncio to see if the process was speeding up a little but nothing. So I was wandering if multiprocessing package was a good solution. Unfortunately until now it gives me always an error:

Traceback (most recent call last):
  File "C:/Users/eepi0002/PycharmProjects/train/Proiection_asyncio.py", line 207, in <module>
    tree_array1.start()
  File "C:\Users\eepi0002\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\eepi0002\AppData\Local\Programs\Python\Python38\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\eepi0002\AppData\Local\Programs\Python\Python38\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\eepi0002\AppData\Local\Programs\Python\Python38\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\eepi0002\AppData\Local\Programs\Python\Python38\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle 'Metashape.Metashape.Camera' object

Do you have any Idea?
Thank you in advance.
Best regards.
Emanuele Papucci.

3
Hi everyone,

Sorry for bother you again, I have a problem with this script to evaluate images quality, because the name and method are changed over the versions of this program, and now I didn't find any good example to help me understand how to use this command better:

This is a for cycle, I just post the final part of the script where is the problem... because I don't know how to use this Metashape command.
The principal problem is this analyzePhotos that doesn't work, in fact, I made several try but every time this function give me a None result, and if I use float he tell me that I can't use this function because the data it's a none type, and this is normal...

Someone can help me to understand? thank you in advance,
Best regards.

Code: [Select]

                  if dist < mindis:
            mindis = dist
            mincam = camera
            mincam.label = camera.label  # camera with min distance to Principal Point
            selcam.append(mincam)  # append all the important parameters in a list of lists.
            plt.show()

    mincam.selected = True
   
    for IMAGE in selcam:
       
        if float(Metashape.Chunk.analyzePhotos(chunk, IMAGE)) < 0.7:
             print("IMAGE")


         

4
Hi everyone,

I'm sorry, I have a big problem, and after 2 days of research into this forum, I decide to ask directly a possible solution of this problem.

I need to crop a part of a camera image that I selected, using a polygon and save it, the problem is that I don't understand how make this crop.

this is part of my script, that I need to complete, there is someone that can help me?

Thank you in advance for your help!
Best regards.

   
Code: [Select]
          #starting work with single tree:
    tree = []
    def find_tree(trees, x):
        count = 0
        for char in trees:
            if char[0] == x[0]:
                print(True)
                point = Metashape.Vector(char[1])  # point of interest
                a = T.inv().mulp(crs.unproject(point))
                b = mincam.transform.inv().mulp(a)
                coords_2D = mincam.sensor.calibration.project(b)
                tree.append(coords_2D)
                count = count - count
            elif char[0] != x[0]:
                # print(False)
                count += 1
                if count == 200:
                    print(count)
                    return tree


    tree1 = find_tree(trees, x)
    print(tree1)

    # crop of the selected images for single chunk:

    img = mincam.image()
    if img.data_type == 'U8':
        ext = '.jpg'
        dtype = numpy.uint8
    if img.data_type == 'U16':
        dtype = numpy.uint16
        ext = '.tif'
    if img.data_type == 'F32':
        ext = '.tif'
        dtype = numpy.float32

    # for x in tree1:
    #     print(x)

    poly = Metashape.Geometry.Polygon(tree1)
    print(poly)

    tree_final = []
    # list_of_vectors = [(v.x, v.y) for v in tree1]
    for v in tree1:
        tree_final.extend([[v.x, v.y]])
    print(tree_final)

    narr = np.array(tree_final)
    print(narr)
   

5
Hi everyone,

I return here, to ask a second question for my project. In fact now, I have a working algorithm that give me a list of best image for each 3d mark convert in 2d coordination. You can see the script below. Now ne problem is if it's possible sing the camera that I found with the algorithm to cut off for each camera of interest a piece of the best image. For do this I need to use My 2d coordinate for each mark, and create a buffer shape mask to use for cut off the selected image.

My working script for now it's this:

Code: [Select]
import Metashape
import csv


path = "I:/Backsjon190527/save_progress/"
doc = Metashape.Document()
doc.open(path + "Finale.psx")
chunk = doc.chunk
crs = chunk.crs
T = chunk.transform.matrix
print(crs)


csvfile = 'I:/Backsjon190527/save_progress/hs1.csv'
def ReadCSVasList(csvfile):
    try:
        with open(csvfile) as csv_file:
            reader = csv.reader(csv_file, dialect='excel')
            datalist = []
            datalist = list(reader)
            return datalist
    except IOError as err:
            print("I/O error({0})".format(err))


csv_data_list = ReadCSVasList(csvfile)
print(csv_data_list)
# To Ignore 1st Element (Headers)
csv_data_list.pop(0)
print(csv_data_list)

result = []

for x in csv_data_list:
        x.pop(0)
print(csv_data_list)

for i in range(0, len(csv_data_list), 1):
   result.append(list(map(float, csv_data_list[i])))

print(result)

selcam = list()

for x in result:
    ## script to find the best image near each marker in the Vector list.
    P = Metashape.Vector(x)  # point of interest in geographic coord
    mindis = 1e09
    # P = Metashape.Vector((459307.345426, 7192625.624622, 158.808)) # vector with X,Y,Z coordinates of point in same CRS as chunk ( I need to understand )
    cam_dist_P = {}  # dict containing  distance in pixels of P to each camera Principal Point

    for camera in chunk.cameras:
        sensor = camera.sensor
        w = sensor.width
        h = sensor.height
        cx = sensor.calibration.cx  # Principal point coordinates x
        cy = sensor.calibration.cy  # Principal point coordinates y
        if not camera.project(T.inv().mulp(chunk.crs.unproject(P))):  # check if projected Point within sensor size
            continue
        xp = camera.project(T.inv().mulp(chunk.crs.unproject(P))).x  # Prrojected point coordinates x
        yp = camera.project(T.inv().mulp(chunk.crs.unproject(P))).y  # Prrojected point coordinates y
        if xp < 0 or xp > w or yp < 0 or yp > h:  # check if projected PointI within sensor size
            continue
        dist = (camera.project(T.inv().mulp(chunk.crs.unproject(P))) - Metashape.Vector(
            (w / 2 + cx, h / 2 + cy))).norm()  # distance in pixels from projected point and P
        cam_dist_P[camera.label] = dist
        if dist < mindis:
            mindis = dist
            mincam = camera  # camera with min distance to Principal Point

    selcam.append(mincam)
        # for image in mincam:


        # Metashape.ModelKeyPoint(Metashape.PointCloud.renderImage(selcam), x)


    print(mincam)

    mincam.selected = True


print(selcam)


This script give to me this result:

[<Camera '100_0015_0047'>, <Camera '100_0015_0047'>, <Camera '100_0015_0048'>, <Camera '100_0015_0036'>, <Camera '100_0015_0036'>, <Camera '100_0015_0049'>, <Camera '100_0015_0048'>, <Camera '100_0015_0046'>, <Camera '100_0015_0046'>, <Camera '100_0015_0040'>, <Camera '100_0015_0047'>, <Camera '100_0015_0045'>, <Camera '100_0015_0040'>, <Camera '100_0015_0040'>, <Camera '100_0015_0046'>].

For the new problem I found on the metashape python reference manual some probably use full commands like these:


Code: [Select]
# c = Metashape.ImageCompression()
# c.jpeg_quality = 50
# chunk.cameras[mincam].image().save(path + fr"{test50}.jpg", c) #create a loop for new file names saving for each cutted image.
Metashape.Mask

# new_shape = chunk.shapes.addShape() #create a new mask shape to cut off a chunk of the selected photo.
# new_shape.type = Metashape.Shape.Polygon
# new_shape.has_z = False
# new_shape.center = [xxx] #center for the new shape?



Someone can give me some advice, or have any Idea to how continue this work?
Thank you in advance to who will help me!
Best regards,
Emanuele.

6
Hello everyone,

I start a project where I need to project some 3D coordinates ( that I don't have on metashape, but in a csv.file) on 2d areal camera/image using python linked to a metashape project. Then I need to cut off and save the best areal image were each point is projected, so I will have a folder with all the best image of the single point in the map.

Someone can help me?

I started using this script that I saw in another post here in the forum:

Code: [Select]
import Metashape, math, csv

path = "I:/Backsjon190527/save_progress/"
doc = Metashape.Document()
doc.open(path + "Finale.psx")
chunk = doc.chunk
crs = chunk.crs
print(crs)

# export format:
# point_ID X Y Z
# [camera_label x_proj y_proj]

M = chunk.transform.matrix
point_cloud = chunk.point_cloud
projections = point_cloud.projections
points = point_cloud.points
npoints = len(points)
print(npoints)
tracks = point_cloud.tracks



path1 = Metashape.app.getSaveFileName(path + 'New.csv',
                                     filter="Text / CSV (*.txt *.csv);;All files (*.*)")
file = open("New.csv", 'wt')

print("Script started...")

point_ids = [-1] * len(point_cloud.tracks)
for point_id in range(0, npoints):
    point_ids[points[point_id].track_id] = point_id
points_proj = {}

for photo in chunk.cameras:

    if not photo.transform:
        continue
    T = photo.transform.inv()
    calib = photo.sensor.calibration

    for proj in projections[photo]:
        track_id = proj.track_id
        point_id = point_ids[track_id]

        if point_id < 0:
            continue
        if not points[point_id].valid:  # skipping invalid points
            continue

        point_index = point_id
        if point_index in points_proj.keys():
            x, y = proj.coord
            points_proj[point_index] = (points_proj[point_index] + "\n" + photo.label + "\t{:.2f}\t{:.2f}".format(x, y))

        else:
            x, y = proj.coord
            points_proj[point_index] = ("\n" + photo.label + "\t{:.2f}\t{:.2f}".format(x, y))

for point_index in range(npoints):

    if not points[point_index].valid:
        continue

    coord = M * points[point_index].coord
    coord.size = 3
    if chunk.crs:
        # coord
        X, Y, Z = chunk.crs.project(coord)
    else:
        X, Y, Z = coord

    line = points_proj[point_index]

    file.write("{}\t{:.6f}\t{:.6f}\t{:.6f}\t{:s}\n".format(point_index, X, Y, Z, line))


file.close()
print("Finished")

This code probably is not good for what I want to do...

Thank you in advance for who will help me!
Best regard.
Emanuele.

Pages: [1]