Python Forum

Full Version: How to address a folder???
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am complately neawby form python,please help

My file is stored in "C:\Users\metbe\OneDrive\Desktop\RPA\download\DM2.jpg"

i need work with this file,

how can i address this file the code herebelow, Angel
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      rakesh.sv
#
# Created:     12-09-2019
# Copyright:   (c) rakesh.sv 2019
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import numpy as np
from skimage import io
from skimage.feature import canny
from skimage.color import rgb2gray
from skimage.transform import hough_line, hough_line_peaks
from skimage.transform import rotate
import skimage
import os
import json
import base64
from base64 import b64encode
from json import dumps
from io import BytesIO
from PIL import Image

class Main():
    def __init__(self):
        self.piby4 = np.pi / 4

    def check_path(self, path):
        if os.path.isabs(path):
            full_path = path
        else:
            full_path = os.getcwd() + '/' + str(path)
        return full_path

    def calculate_deviation(self,angle):
        angle_in_degrees = np.abs(angle)
        deviation = np.abs(self.piby4 - angle_in_degrees)
        return deviation

    def get_max_freq_elem(self,arr):
        max_arr = []
        freqs = {}
        for i in arr:
            if i in freqs:
                freqs[i] += 1
            else:
                freqs[i] = 1
        sorted_keys = sorted(freqs, key=freqs.get, reverse=True)
        max_freq = freqs[sorted_keys[0]]
        for k in sorted_keys:
            if freqs[k] == max_freq:
                max_arr.append(k)
        return max_arr

    def compare_sum(self,value):
        if value >= 44 and value <= 46:
            return True
        else:
            return False

    def predict(self,input_path):
        try:
            img = skimage.io.imread(input_path,as_gray=True, plugin='imageio')
            edges = canny(img, sigma=3.0)
            ##hspace , angle , distance
            h, a, d = hough_line(edges)
            ## accum, angles, dists
            _, ap, _ = hough_line_peaks(h, a, d, num_peaks=20)
            if len(ap) == 0:
                pil_img = Image.fromarray(img)
                buff = BytesIO()
                pil_img.save(buff, format="PNG")
                new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
                return json.dumps({"Angle":0.0,"Base64":new_image_string})
            absolute_deviations = [self.calculate_deviation(k) for k in ap]
            average_deviation = np.mean(np.rad2deg(absolute_deviations))
            ap_deg = [np.rad2deg(x) for x in ap]
            bin_0_45 = []
            bin_45_90 = []
            bin_0_45n = []
            bin_45_90n = []
            for ang in ap_deg:
                deviation_sum = int(90 - ang + average_deviation)
                if self.compare_sum(deviation_sum):
                    bin_45_90.append(ang)
                    continue

                deviation_sum = int(ang + average_deviation)
                if self.compare_sum(deviation_sum):
                    bin_0_45.append(ang)
                    continue

                deviation_sum = int(-ang + average_deviation)
                if self.compare_sum(deviation_sum):
                    bin_0_45n.append(ang)
                    continue

                deviation_sum = int(90 + ang + average_deviation)
                if self.compare_sum(deviation_sum):
                    bin_45_90n.append(ang)

            angles = [bin_0_45, bin_45_90, bin_0_45n, bin_45_90n]
            lmax = 0
            for j in range(len(angles)):
                l = len(angles[j])
                if l > lmax:
                    lmax = l
                    maxi = j

            if lmax:
                ans_arr = self.get_max_freq_elem(angles[maxi])
                ans_res = np.mean(ans_arr)
            else:
                ans_arr = self.get_max_freq_elem(ap_deg)
                ans_res = np.mean(ans_arr)

            data = {
                "Image File": "",
                "Average Deviation from pi/4": average_deviation,
                "Estimated Angle": ans_res,
                "Angle bins": angles}
            angle = data['Estimated Angle']
            if angle!="":
                if angle >= 0 and angle <= 90:
                    rot_angle = angle - 90
                if angle >= -45 and angle < 0:
                    rot_angle = angle - 90
                if angle >= -90 and angle < -45:
                    rot_angle = 90 + angle
                rotated = rotate(img, rot_angle, resize=True,mode='edge')
                higher_dtype = (rotated*255)
                h_dtype = higher_dtype.astype(np.uint8)
                pil_img = Image.fromarray(h_dtype)
                buff = BytesIO()
                pil_img.save(buff, format="PNG")
                new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
##                file_name=os.path.basename(os.path.normpath(input_path))
##                directory_path = os.path.dirname(path)
##                output_path = directory_path+"\\"+"Corrected_"+file_name
##                io.imsave(output_path, higher_dtype.astype(np.uint8))
                return json.dumps({"Angle":rot_angle,"Base64":new_image_string})
            else:
                return json.dumps({"Angle":"Image quality not supported","Base64":""})
        except Exception as e:
##          return json.dumps(str(e), indent=2)
            return json.dumps({"Angle":"Image quality not supported","Base64":""})

##if __name__ == '__main__':
##    path = "C:\\Users\\rakesh.sv\\Desktop\\Skew_images\\Corrected_skew_sample.png"
##    output_path"C:\\Users\\rakesh.sv\\Desktop\\Skew_images\\skew_sample5_corrected.jpg"
##    obj = Main()
##    x =obj.predict(path)
##    print(x)
where is the file in relation to the python script?