0

I want to display length according to part 1 Image. but now its making like part 2. I am using below code.

    import shapefile
from PIL import Image,ImageDraw, ImageFont
from qgis.utils import iface
from PyQt4.QtCore import QVariant
import math
import psycopg2
try:
    conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='mindcrew01'")
except:
    print "I am unable to connect to the database"

cur = conn.cursor()
r = shapefile.Reader("K:\NEW_GIS\Arkund\Arkund\ESRI SHAPE FILE\ADJUJICATION\Final\Arkund_Corr")
shapes = r.shapes()
layer = iface.activeLayer()
feature_dict = {f.id(): f for f in layer.getFeatures()}
index = QgsSpatialIndex()
for f in feature_dict.values():    
    index.insertFeature(f)


Chalata_array=[]
neighbors_chalata_array={}
neighbors_pixels_array={}
points_full_array={}
for f in feature_dict.values():
    polygon_f_id=[]
    polygon_f_id.append(f.id())
    Chalata_array.append(f['STRING_'])
    neighbors_chalata_first=[]
    neighbors_chalata_first.append(f['STRING_'])
    geom = f.geometry()
    points_full_array_first=[]
    intersecting_ids = index.intersects(geom.boundingBox())
    for intersecting_id in intersecting_ids:
        intersecting_f = feature_dict[intersecting_id]      
        if (f != intersecting_f and not intersecting_f.geometry().disjoint(geom)):
            neighbors_chalata_first.append(intersecting_f['STRING_'])
            polygon_f_id.append(intersecting_f.id())

    iwidth = 680
    iheight = 449   
    xdist =shapes[f.id()].bbox[2] - shapes[f.id()].bbox[0]
    ydist =shapes[f.id()].bbox[3] - shapes[f.id()].bbox[1]
    xratio = (iwidth/(xdist+82))
    yratio = (iheight/(ydist+15))
    neighbors_pixels_first={}
    for get_id in range(len(polygon_f_id)): 
        neighbors_pixels_secound=[]
        for x,y in r.shapes()[polygon_f_id[get_id]].points:         
            px = int((iwidth - ((shapes[polygon_f_id[0]].bbox[2] - x) * xratio)-100))
            py = int(((shapes[polygon_f_id[0]].bbox[3] - y) * yratio)+30)       
            neighbors_pixels_secound.append((px,py))
            points_full_array_first.append((px,py))
        neighbors_pixels_first[get_id]=neighbors_pixels_secound

    points_full_array[f['STRING_']]=points_full_array_first     
    neighbors_chalata_array[f['STRING_']]=neighbors_chalata_first   
    neighbors_pixels_array[f['STRING_']]=neighbors_pixels_first


#print points_full_array
#print neighbors_chalata_array
#print neighbors_pixels_array


for chalata_no_i in range(len(Chalata_array)):
    fnt = ImageFont.truetype('C:\example\GJBWAV0B.ttf', 30)
    fnt_new = ImageFont.truetype('C:\example\GJBWAV0B.ttf', 15) 
    img = Image.new("RGB", (iwidth, iheight), "white")
    draw = ImageDraw.Draw(img)
    image_name=Chalata_array[chalata_no_i]  
    for new_chalata_no in range(len(neighbors_pixels_array[Chalata_array[chalata_no_i]])):
        if(new_chalata_no==0):
            get_pixels=neighbors_pixels_array[Chalata_array[chalata_no_i]][new_chalata_no]
            max_point_x=max(get_pixels)
            min_point_y=min(get_pixels)
            n = len(get_pixels) # of corners
            area = 0.0
            for i in range(n):
                j = (i + 1) % n
                area += get_pixels[i][0] * get_pixels[j][1]
                area -= get_pixels[j][0] * get_pixels[i][1]
            area = abs(area) / 2.0

            #new_area=area/1000
            cur.execute("SELECT id FROM maap_chalta_no where district=%s and taluka=%s and village=%s and Chalto_Number=%s",("તાપી","વ્યારા","આરકુંડ",Chalata_array[chalata_no_i]))
            #print cur.fetchone()[0]
            if(cur.rowcount>0):
                cur.execute("UPDATE maap_chalta_no SET maap_number=%s WHERE id=%s",(area, cur.fetchone()[0]))
            else:
                query_three = "INSERT INTO maap_chalta_no (district,taluka,village,Chalto_Number,maap_number) VALUES (%s, %s, %s, %s, %s)"
                values_three = ("તાપી","વ્યારા","આરકુંડ", Chalata_array[chalata_no_i], area)
                # Execute sql Query
                cur.execute(query_three, values_three)
            conn.commit()
            x = [p[0] for p in get_pixels]
            y = [p[1] for p in get_pixels]
            centroid = (sum(x) / len(get_pixels), sum(y) / len(get_pixels))
            draw.text(centroid, str(neighbors_chalata_array[Chalata_array[chalata_no_i]][new_chalata_no]), font=fnt, fill='black')
            line_x=""
            line_y=""
            for get_line_point in range(len(get_pixels)):
                if(get_line_point!=0):
                    lin_points_array=[(line_x,line_y),(get_pixels[get_line_point][0],get_pixels[get_line_point][1])]
                    draw.line(lin_points_array, fill="black", width=4)
                    x_line = [p[0] for p in lin_points_array]
                    y_line = [p[1] for p in lin_points_array]
                    centroid_new = ((sum(x_line) /2), (sum(y_line) /2))
                    line_length=math.hypot(get_pixels[get_line_point][0] - line_x, get_pixels[get_line_point][1]-line_y)
                    new_line_length=line_length/3.28084
                    if(new_line_length>10):
                        org_length="{:.2f}".format(new_line_length)
                        #new_org_length=org_length.split('.')
                        #new_new_org_length=new_org_length[0]+' .'+new_org_length[1]
                        draw.text(centroid_new, org_length, font=fnt_new, fill='black')
                line_x=get_pixels[get_line_point][0]
                line_y=get_pixels[get_line_point][1]
        else:
            #print new_chalata_no
            get_pixels=neighbors_pixels_array[Chalata_array[chalata_no_i]][new_chalata_no]
            x = [p[0] for p in get_pixels]
            y = [p[1] for p in get_pixels]
            centroid = (sum(x) / len(get_pixels), sum(y) / len(get_pixels))
            draw.text(centroid, str(neighbors_chalata_array[Chalata_array[chalata_no_i]][new_chalata_no]), font=fnt, fill='black')
            line_x=""
            line_y=""
            for get_line_point in range(len(get_pixels)):
                if(get_line_point!=0):
                    if(((get_pixels[get_line_point][0],get_pixels[get_line_point][1]) in neighbors_pixels_array[Chalata_array[chalata_no_i]][0])== False):
                        lin_points_array=[(line_x,line_y),(get_pixels[get_line_point][0],get_pixels[get_line_point][1])]
                        draw.line(lin_points_array, fill="black", width=1)
                        x_line = [p[0] for p in lin_points_array]
                        y_line = [p[1] for p in lin_points_array]
                        centroid_new = ((sum(x_line) / len(lin_points_array)), (sum(y_line) / len(lin_points_array))-20)
                        line_length=math.hypot(get_pixels[get_line_point][0] - line_x, get_pixels[get_line_point][1]-line_y)
                        new_line_length=line_length/3.28084
                        if(new_line_length>10):
                            org_length="{:.2f}".format(new_line_length)
                            #new_org_length=org_length.split('.')
                            #new_new_org_length=new_org_length[0]+' .'+new_org_length[1]
                            draw.text(centroid_new, org_length, font=fnt_new, fill='black')
                line_x=get_pixels[get_line_point][0]
                line_y=get_pixels[get_line_point][1]



    img_new_name="C:/example/Images/Chalta_no_"+str(image_name)+".png"
    img.save(img_new_name, quality=150)

enter image description here

1

Do I understand correctly, you want to draw the labels parallel to the lines?

A very similar question has just been answered today - How to label individual sides of a polygon , using QGIS itself. This might be an easier way to achieve this.

I see you're using PIL to do this rendering. Does this answer help?

If you want to use PIL, you'll need to be able to work out the rotation angle for each edge. I'd recommend you look at QgsPoint and its azimuth() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.