Ejemplo n.º 1
0
def ProcessImages():
    #############
    #Step 3
    #############
    #Here for the images we downloaded in the step1 we are applying gradient effect
    print('check0')
    list_of_elements = os.listdir('.')
    list_of_elements = natsort.natsorted(list_of_elements)
    list_of_elements_new = []
    gradient_magnitude = 2.25
    test = (8, 8, 10)
    print('check1')
    for item in list_of_elements:
        if item.endswith('.jpg') and item != '1.jpg' and item != 'custom2.jpg':
            img_original = image.load_img(item, target_size=(730, 1180, 3))
            try:
                if brisque.score(img_original) < 55:
                    print(brisque.score(img_original))
                    list_of_elements_new.append(
                        [item, brisque.score(img_original)])
            except Exception:
                print("Image not included")
    print('check2')
    list_of_elements_new = sorted(list_of_elements_new, key=lambda x: x[1])

    if len(list_of_elements_new) >= 5:
        list_of_elements_new = list_of_elements_new[:5]

    list_of_elements_new = [item[0] for item in list_of_elements_new]

    for images in list_of_elements_new:
        im = Image.open(images)
        width, height = im.size
        if im.mode != 'RGBA':
            im = im.convert('RGBA')
        width, height = im.size
        gradient = Image.new('L', (1, height), color=0xFF)
        for x in range(height):
            gradient.putpixel(
                (0, x),
                int(255 * (1 - gradient_magnitude * float(x) / height)))
        alpha = gradient.resize(im.size)
        alpha = alpha.rotate(180)
        black_im = Image.new('RGBA', (width, height), color=test)
        black_im.putalpha(alpha)
        gradient_im = Image.alpha_composite(im, black_im)
        gradient_im = gradient_im.convert(
            "RGB")  #Wrote newly as not working with RGBA
        gradient_im.save(images)
    return list_of_elements, list_of_elements_new
Ejemplo n.º 2
0
def Referenssless_Image_Quality_Assessment():
    Galeries_Matrix = np.array(galeries).reshape(len(Countries),10)

    valid_images = [".jpg",".gif",".png"]
    
    QScores = []

    i = 0
    for Country in Countries:
        print(str(i+1) + ' : ' + Country)
        for j in range (10):
            path = DataSet+'/'+Country+'/'+Galeries_Matrix[i,j]+'/'
            
            for f in os.listdir(path):
                ext = os.path.splitext(f)[1]
                if ext.lower() in valid_images:    
                   img = PIL.Image.open(path+f)
                   Q = brisque.score(img)
                   QScores.append(Q)
        i+=1
    pickle_out = open("QScores.pkl","wb")
    pickle.dump(QScores, pickle_out)
    pickle_out.close()
    
    return QScores
Ejemplo n.º 3
0
def upload():
    if request.method == 'POST':
        # Get the file from post request
        f = request.files['file']

        # Save the file to ./uploads
        basepath = os.path.dirname(__file__)
        file_path = os.path.join(
            basepath, 'uploads', secure_filename(f.filename))
        f.save(file_path)

        img = PIL.Image.open(file_path)
        result=brisque.score(img)

        if result < 0:
            result = 0

        if result > 100:
            result = 100

        # reverse result
        # near 100 -- means best quality
        # near 0   -- means low quality
        result = (100 - result)
        
        result=(str(result))
        return result
    return None
Ejemplo n.º 4
0
def calculate_scores(arg):
    """
    Calculeaza scorul calitatii imaginilor aflate la path-urile primite
    :param arg: poate sa fie, fie o lista de path-uri de imagini, fie un director ce contine imaginile
    :return: Nothing, just prints the scores
    """

    list_of_scores = []

    if isinstance(arg, list):
        images_path = arg

        for image_path in images_path:
            print("Processing image {} ...".format(image_path))

            img = PIL.Image.open(image_path)
            img_score = int(brisque.score(img))

            list_of_scores.append(img_score)

    elif os.path.isdir(arg):
        images_path = os.listdir(arg)

        list_of_scores = []

        for image_path in images_path:

            image_path = os.path.join(arg, image_path)

            print("Processing image {} ...".format(image_path))

            img = PIL.Image.open(image_path)
            img_score = int(brisque.score(img))

            list_of_scores.append(img_score)

    elif os.path.isfile(arg):
        img = PIL.Image.open(arg)
        img_score = int(brisque.score(img))

        list_of_scores = [img_score]
    else:
        raise Exception(
            "Argumentul nu este nici lista, nici path de imagine, nici director!"
        )

    return list_of_scores, sum(list_of_scores) / len(list_of_scores)
Ejemplo n.º 5
0
def add_image_to_dict(full_url: str):
    try:
        image_response = requests.get(full_url)
        img = Image.open(BytesIO(image_response.content))
        image_score = brisque.score(img)
        images_score[full_url] = image_score
    except Exception as e:
        print(e)
Ejemplo n.º 6
0
def calc_brisque(df):
    for row in df[df["brisque"].isnull()].itertuples():
        image = Image.open(row.Index)
        score = brisque.score(image)
        print(row.Index, score)
        df.loc[row.Index, "brisque"] = score

    return df
Ejemplo n.º 7
0
 def __call__(self, img: np.ndarray) -> float:
     try:
         import imquality.brisque as brisque
     except ImportError:
         raise UnsupportedExperiment(
             "Brisque is not installed, please run 'pip install imquality'")
     try:
         score = brisque.score(img)
     except AssertionError:  # oh my god, brisque can raise an assert when the data is too weird.
         score = float("inf")
     return score
Ejemplo n.º 8
0
 def get_quality(self, faces) -> int:
     """
     :return max quality of extracted faces
     """
     faces = self.extract_faces(faces)
     if not faces:
         return 0
     quality = 0
     for face in faces:
         quality = max(brisque.score(face), quality)
     return quality
Ejemplo n.º 9
0
def score_image(image_path: AnyStr) -> float:
    is_url = image_path.lower().startswith("http")
    logger.info("%s is url: %s", image_path, is_url)
    if is_url:
        # see https://stackoverflow.com/questions/22340265/python-download-file-using-requests-directly-to-memory
        r = requests.get(image_path, stream=True)
        logger.info("[%s]: %s", r.status_code, image_path)
        r.raw.decode_content = True  # Content-Encoding
        img = Image.open(r.raw)
    else:
        # for local path
        img = Image.open(image_path)
    return brisque.score(img)
Ejemplo n.º 10
0
def image_quality(image_path):

    # path for reading
    root = "djangoProject"
    path = root + image_path

    image = PIL.Image.open(path)
    result = brisque.score(image)

    #THE MEAN VALUE NEEDED TO B ASSIGNED
    # lower the number  = less pixelated
    # however, the blurry images do not work in this
    return result
Ejemplo n.º 11
0
def sort_by_quality_of_image(path):
    file_list = os.listdir(path)
    for index, filename in enumerate(file_list):
        img = PIL.Image.open(path + '/' + filename)
        score = brisque.score(img)
        print('Score for image {} is {}'.format(filename, score))

        if 0 < score <= 10.0:

            if not os.path.exists(path+"/0-10"):
                os.makedirs(path + '/0-10')
                print("dir created@", path + '/0-10')
            shutil.copy(path + '/' + filename, path + '/0-10/' + filename)
        elif 10 < score <= 20.0:
            if not os.path.exists(path+"/10-20"):
                os.makedirs(path + '/10-20')
            shutil.copy(path + '/' + filename, path + '/10-20/' + filename)
        elif 20 < score <= 30.0:
            if not os.path.exists(path+"/20-30"):
                os.makedirs(path + '/20-30')
            shutil.copy(path + '/' + filename, path + '/20-30/' + filename)
        elif 30 < score <= 40.0:
            if not os.path.exists(path+"/30-40"):
                os.makedirs(path + '/30-40')
            shutil.copy(path + '/' + filename, path + '/30-40/' + filename)
        elif 40 < score <= 50.0:
            if not os.path.exists(path+"/40-50"):
                os.makedirs(path + '/40-50')
            shutil.copy(path + '/' + filename, path + '/40-50/' + filename)
        elif 50 < score <= 60.0:
            if not os.path.exists(path+"/50-60"):
                os.makedirs(path + '/50-60')
            shutil.copy(path + '/' + filename, path + '/50-60/' + filename)
        elif 60 < score <= 70.0:
            if not os.path.exists(path+"/60-70"):
                os.makedirs(path + '/60-70')
            shutil.copy(path + '/' + filename, path + '/60-70/' + filename)
        elif 70 < score <= 80.0:
            if not os.path.exists(path+"/70-80"):
                os.makedirs(path + '/70-80')
            shutil.copy(path + '/' + filename, path + '/70-80/' + filename)
        elif 80 < score <= 90.0:
            if not os.path.exists(path+"/80-90"):
                os.makedirs(path + '/80-90')
            shutil.copy(path + '/' + filename, path + '/80-90/' + filename)
        elif 90 < score <= 100.0:
            if not os.path.exists(path+"/90-100"):
                os.makedirs(path + '/90-100')
            shutil.copy(path + '/' + filename, path + '/90-100/' + filename)
def image_quality(image_path):
    # path = r"C:\DIT\FYP\102flowers\sample-low-quality\blurry.jpg"
    begin = cv2.os.getcwd()
    image_root = begin.replace("\\", "/")

    path = image_root + image_path

    image = PIL.Image.open(path)
    # image.show()
    result = brisque.score(image)

    # print(result)
    # print("this is the path")
    # print(type(path))
    # print(path)
    # lower the number  = less pixelated
    # however, the blurry images do not work in this
    return result
Ejemplo n.º 13
0
def IQA_cal():
    process_box.delete(0, tk.END)
    path = entryText_1.get()

    gene_img = path + "gene\\"
    gt_img = path + "gt\\"
    img = make_dataset(gene_img)
    ori = make_dataset(gt_img)
    IQA_num_list = [0.0, 0.0, 0.0, 0.0]  #psnr ssim brisque niqe
    count = 0

    for gene, gt_img in zip(img, ori):
        state.configure(text="State.....Calculating")
        dehaze = cv2.imread(gene)
        gt = cv2.imread(gt_img)

        BRI = brisque.score(dehaze)
        psnr = cv2.PSNR(gt, dehaze)
        ssim = compare_ssim(gt, dehaze, multichannel=True)
        niqe_num = ni.niqe(dehaze)

        result = gene.split("\\")[-1]
        result += "...done"
        process_box.insert(count, result)
        process_box.see(count)

        IQA_num_list[0] += psnr
        IQA_num_list[1] += ssim
        if BRI >= 0:
            IQA_num_list[2] += BRI
        IQA_num_list[3] += niqe_num
        count += 1

    str_list = ['PSNR avg : ', 'SSIM avg :', 'BRI avg : ', 'niqe avg : ']
    total = len(img)

    for num, strz in zip(IQA_num_list, str_list):
        process_box.insert(count, strz + str(round(num / total, 4)))
        process_box.see(count)
        count += 1

    process_box.see(count + 1)
    state.configure(text="State.....Waiting")
Ejemplo n.º 14
0
    def generate_img_scores(self, path):
        ''' 
		Generates the image quality scores for all images in the given folder using BRISQUE and stores it in a dictionary.
		Args : 
			path : (string) path to the processedData folder.
		'''

        for i in os.listdir(path):
            img_path = os.path.join(path, i)
            img = cv2.imread(img_path, 0)

            if self.image_quality == "brisque":
                try:
                    img_score = brisque.score(img)
                except Exception as e:
                    print(f"Unable to calculate BRISQUE socre due to {e}")

            elif self.image_quality == "entropy":
                try:
                    entropy = []
                    hist = cv2.calcHist([img], [0], None, [256], [0, 255])
                    total_pixel = img.shape[0] * img.shape[1]
                    for item in hist:
                        probability = item / total_pixel
                        if probability == 0:
                            en = 0
                        else:
                            en = -1 * probability * (np.log(probability) /
                                                     np.log(2))
                        entropy.append(en)
                    img_score = np.sum(entropy)[0]
                except Exception as e:
                    print(f"Unable to calculate Entropy socre due to {e}")

            # add score and image name to dictionary after rounding it off
            self.image_scores[i] = format(img_score, '.2f')
Ejemplo n.º 15
0
Mittal, A., A. K. Moorthy, and A. C. Bovik. "No-Reference Image Quality Assessment in the Spatial Domain.
" IEEE Transactions on Image Processing. Vol. 21, Number 12, December 2012, pp. 4695–4708.
https://live.ece.utexas.edu/publications/2012/TIP%20BRISQUE.pdf

To install imquality
https://pypi.org/project/image-quality/
"""
import numpy as np
from skimage import io, img_as_float
import imquality.brisque as brisque

#img = img_as_float(io.imread('noisy_images/BSE.jpg', as_gray=True))
img = img_as_float(
    io.imread('images/noisy_images/sandstone_25sigma_noisy.tif', as_gray=True))

score = brisque.score(img)
print("Brisque score = ", score)

#Now let us check BRISQUE scores for a few blurred images.

img0 = img_as_float(
    io.imread('images/blurred_images/sandstone.tif', as_gray=True))
img2 = img_as_float(
    io.imread('images/blurred_images/sandstone_2sigma_blur.tif', as_gray=True))
img3 = img_as_float(
    io.imread('images/blurred_images/sandstone_3sigma_blur.tif', as_gray=True))
img5 = img_as_float(
    io.imread('images/blurred_images/sandstone_5sigma_blur.tif', as_gray=True))

score0 = brisque.score(img0)
score2 = brisque.score(img2)
Ejemplo n.º 16
0
def test_correct_score_calculation(file_path, expected):
    image = load_image(os.path.join(TEST_PATH, 'resources', file_path))
    assert score(image) == pytest.approx(expected, 3)
Ejemplo n.º 17
0
 def __call__(self, img: np.ndarray) -> float:
     try:
         score = brisque.score(img)
     except AssertionError:  # oh my god, brisque can raise an assert when the data is too weird.
         score = float("inf")
     return score
Ejemplo n.º 18
0
def BRISQUE(img):
    img = Image.fromarray(np.uint8(img.squeeze(0).transpose(1, 2, 0)))
    bris_score = bris.score(img)
    return bris_score
Ejemplo n.º 19
0
    bbox = diff.getbbox()
    # if bbox:
    #     return im.crop(bbox)
    return bbox != (0, 0, im.size[0], im.size[1])


image = cv2.imdecode(cv_img, cv2.IMREAD_COLOR)
height, width, _ = image.shape
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
reshape = image.reshape((image.shape[0] * image.shape[1], 3))

_cluster = KMeans(n_clusters=5).fit(reshape)
visualize = visualize_colors(_cluster, _cluster.cluster_centers_)
img = Image.open(file_name)
_format = img.format
quality = br.score(img)
# volume = os.stat(file_name).st_size
# volume = len(img.fp.read())
volume = meta.get(name="Content-Length")
check_border = check_image_has_border(img)

print({
    'Colors': visualize,
    'Format': _format,
    'Volume': f'{str(volume)} Bytes',
    'Quality': quality,
    'Height': height,
    'Width': width,
    'IsBorderRemoved': check_border
})
Ejemplo n.º 20
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import imquality.brisque as brisque
import PIL.Image

#path = 'path/to/image'
#img = PIL.Image.open(path)
#res = brisque.score(img)
#print('Score =', res)

import os
import glob
files = list(glob.glob(os.path.join("images", '*.*')))
print(files)
theimages = files

for x in theimages:
    img = PIL.Image.open(x)
    res = brisque.score(img)
    print('Score =', x, res)
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 16:58:37 2020

@author: Ashok
"""

import imquality.brisque as brisque
import PIL.Image as Image
import os

path = r'C:\Users\Ashok\Desktop\ENGI_981_A\Code\real_test_input'

for imagePath in os.listdir(path):
    inputPath = os.path.join(path, imagePath)
    img = Image.open(inputPath)
    score = brisque.score(img)
    print(imagePath, "\t", score)
Ejemplo n.º 22
0
def brisque_score(image):
    return brisque.score(image)
Ejemplo n.º 23
0
import os
import imquality.brisque as brisque

path1 = 'C:/Users/Irfan/Documents/01_thesis/ssim_files_FRGC/dim128/01-rwae_samples/'

img_base = []

for root, dirs, files in os.walk(path1):
    dirs.sort(key=int)

    if files == []:
        continue

    for filee in files:
        full_path = os.path.join(root, filee)
        #print(full_path)
        img = cv2.resize(cv2.imread(full_path), (64, 64))
        img = skimage.color.rgb2gray(img)
        img_base.append(img)

img_base = np.array(img_base)

score = 0

for i in range(len(img_base)):
    calc = brisque.score(img_base[i])
    score += calc

print(score)
print(score / len(img_base))
Mittal, A., A. K. Moorthy, and A. C. Bovik. "No-Reference Image Quality Assessment in the Spatial Domain.
" IEEE Transactions on Image Processing. Vol. 21, Number 12, December 2012, pp. 4695–4708.
https://live.ece.utexas.edu/publications/2012/TIP%20BRISQUE.pdf

To install imquality
https://pypi.org/project/image-quality/
"""
import numpy as np
from skimage import io, img_as_float
import imquality.brisque as brisque

#img = img_as_float(io.imread('noisy_images/BSE.jpg', as_gray=True))
img = img_as_float(
    io.imread('noisy_images/BSE_50sigma_noisy.jpg', as_gray=True))

score = brisque.score(img)
print("Brisque score = ", score)

#Now let us check BRISQUE scores for a bunch of blurred images.

img0 = img_as_float(io.imread('noisy_images/BSE.jpg', as_gray=True))
img25 = img_as_float(
    io.imread('noisy_images/BSE_1sigma_blur.jpg', as_gray=True))
img50 = img_as_float(
    io.imread('noisy_images/BSE_2sigma_blur.jpg', as_gray=True))
img75 = img_as_float(
    io.imread('noisy_images/BSE_3sigma_blur.jpg', as_gray=True))
img100 = img_as_float(
    io.imread('noisy_images/BSE_5sigma_blur.jpg', as_gray=True))
img200 = img_as_float(
    io.imread('noisy_images/BSE_10sigma_blur.jpg', as_gray=True))
clear_dir = home + "/Downloads/QA-Polyp/train/0-clear/"

blur_dir = home + "/Downloads/QA-Polyp/train/1-blurry/"

clear_images = os.listdir(clear_dir)

blur_images = os.listdir(blur_dir)

i = 0

for image in clear_images:
    path = clear_dir + image

    img = PIL.Image.open(path)
    print(image + ":" + str(brisque.score(img)))

    i = i + 1

    if i > 10:
        break

i = 0
for image in blur_images:
    path = blur_dir + image

    img = PIL.Image.open(path)
    print(image + ":" + str(brisque.score(img)))

    i = i + 1
Ejemplo n.º 26
0
def brisque_imquality(img):
    return brisque.score(img)
Ejemplo n.º 27
0
def calculate_scores(arg):
    """
    Calculeaza scorul calitatii imaginilor aflate la path-urile primite
    :param arg: poate sa fie, fie o lista de path-uri de imagini, fie un director ce contine imaginile
    :return: Nothing, just prints the scores
    """
    if isinstance(arg, list):
        images_path = arg

        dict_img_scores = {}

        for image_path in images_path:
            print("Processing image {} ...".format(image_path))

            img = PIL.Image.open(image_path)
            img_score = int(brisque.score(img))

            if img_score > 40:
                dict_img_scores[image_path] = (
                    False,
                    "Calitatea imaginii {} are scorul {} ceea ce inseamna o calitate proasta!"
                    .format(image_path, img_score))
            else:
                dict_img_scores[image_path] = (
                    True,
                    "Calitatea imaginii {} are scorul {} ceea ce inseamna o calitate buna!"
                    .format(image_path, img_score))

        return dict_img_scores

    elif os.path.isdir(arg):
        images_path = os.listdir(arg)

        dict_img_scores = {}

        for image_path in images_path:

            image_path = os.path.join(arg, image_path)

            print("Processing image {} ...".format(image_path))

            img = PIL.Image.open(image_path)
            img_score = int(brisque.score(img))

            if img_score > 40:
                dict_img_scores[image_path] = (
                    False,
                    "Calitatea imaginii {} are scorul {} ceea ce inseamna o calitate proasta!"
                    .format(image_path, img_score))
            else:
                dict_img_scores[image_path] = (
                    True,
                    "Calitatea imaginii {} are scorul {} ceea ce inseamna o calitate buna!"
                    .format(image_path, img_score))

        return dict_img_scores

    elif os.path.isfile(arg):
        img = PIL.Image.open(arg)
        img_score = int(brisque.score(img))

        if img_score > 40:
            return (
                False,
                "Calitatea imaginii {} are scorul {} ceea ce inseamna o calitate proasta!"
                .format(arg, img_score))
        else:
            return (
                True,
                "Calitatea imaginii {} are scorul {} ceea ce inseamna o calitate buna!"
                .format(arg, img_score))
    else:
        raise Exception(
            "Argumentul nu este nici lista, nici path de imagine, nici director!"
        )
    blur_dir = home + "/Downloads/QA-Polyp/train/1-blurry/"

    clear_images = os.listdir(clear_dir)

    blur_images = os.listdir(blur_dir)


    i=1

    for image in clear_images:
        path = clear_dir + image

        img = PIL.Image.open(path)

        value = (brisque.score(img))/4



        writer.writerow({'scores': value})

        print(str(i)+":"+str(value))
        i =i+1


    #count -829 for clear
    #233 blur


    for image in blur_images:
        path = blur_dir + image
Ejemplo n.º 29
0
import imquality.brisque as brisque
import PIL.Image
import sys
import os

try:
    path = './uploads/file'
    img = PIL.Image.open(path)
    print(brisque.score(img))
except BaseException as e:
    print(e)
finally:
    os.remove('uploads/file')
    sys.stdout.flush()