Beispiel #1
0
 def test_from_grayscale(self):
     brisque = BRISQUE()
     for idx, path in enumerate(self._paths):
         image = cv2.imread(path, 0)
         self.assertAlmostEqual(brisque.get_score(image),
                                self._score[idx],
                                places=3)
Beispiel #2
0
 def test_from_path(self):
     """Test directly from the path."""
     brisque = BRISQUE()
     for idx, path in enumerate(self._paths):
         self.assertAlmostEqual(brisque.get_score(path),
                                self._score[idx],
                                places=3)
Beispiel #3
0
 def test_scale_feature(self):
     """Test scale the feature from Matlab original code."""
     brisque = BRISQUE()
     for idx, feat in enumerate(self._brisque_feats):
         scaled_feat = brisque._scale_feature(feat)
         np.testing.assert_array_almost_equal(scaled_feat,
                                              self._scaled_feats[idx],
                                              decimal=5)
Beispiel #4
0
 def test_get_feature(self):
     """The feature generated is equal."""
     brisque = BRISQUE()
     for idx, path in enumerate(self._paths):
         image = cv2.imread(path, 0)
         feature = brisque.get_feature(image)
         np.testing.assert_array_almost_equal(feature,
                                              self._brisque_feats[idx],
                                              decimal=0)
def test_brisque_values_grey(device: str) -> None:
    img = imread('tests/assets/goldhill.gif')
    x_grey = torch.tensor(img).unsqueeze(0).unsqueeze(0)
    score = brisque(x_grey.to(device), reduction='none', data_range=255)
    score_baseline = BRISQUE().get_score(img)
    assert torch.isclose(score, torch.tensor(score_baseline).to(score), rtol=1e-3), \
        f'Expected values to be equal to baseline, got {score.item()} and {score_baseline}'
Beispiel #6
0
def test_brisque_values_rgb(device: str) -> None:
    img = imread('tests/assets/I01.BMP')
    x_rgb = (torch.tensor(img, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0))
    score = brisque(x_rgb.to(device), reduction='none', data_range=255.)
    score_baseline = BRISQUE().get_score(x_rgb[0].permute(1, 2, 0).numpy()[..., ::-1])
    assert torch.isclose(score, torch.tensor(score_baseline).to(score), rtol=1e-3), \
        f'Expected values to be equal to baseline, got {score.item()} and {score_baseline}'
Beispiel #7
0
class BRISQUE_Metric_gen(Callback):
    def __init__(self):
        super().__init__()
        self.name = "brisque_gen"
        self.brisque = BRISQUE()

    def on_epoch_begin(self, **kwargs):
        self.values = []

    def on_batch_end(self, last_output, last_target, **kwargs):
        for img in last_output:
            score = self.brisque.get_score(img.permute(1, 2, 0).cpu().numpy())
            self.values.append(score)

    def on_epoch_end(self, last_metrics, **kwargs):
        return add_metrics(last_metrics, sum(self.values) / len(self.values))
Beispiel #8
0
def main(args):
    # get the reference to the webcam
    camera = cv2.VideoCapture(0)
    # ROI coordinates
    img_w = 112
    img_h = 112
    top = 160
    left = 300
    bottom = top + img_h
    right = left + img_w

    image_num = 0

    start_recording = False
    # make a new folder storing images
    today_str = datetime.now().strftime("%y%m%d%H%M%S")
    saving_folder_path = "./" + today_str + '_' + args.file_prefix
    os.mkdir(saving_folder_path)
    saving_img_path = saving_folder_path + '/' + args.file_prefix + '_'
    print("Save images to " + saving_img_path)
    brisq = BRISQUE()
    while(True):
        # get the current frame
        (grabbed, frame) = camera.read()
        if (grabbed == True):
            # fix the frame width to be 640
            frame = imutils.resize(frame, width=640)
            # clone the frame for rendering
            clone = frame.copy()

            # get the ROI
            roi = frame[top:bottom, left:right]

            # convert the roi to grayscale and blur it
            gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
            image_quality = brisq.get_score(gray)
            # sometimes brisq outputs nan, we should ignore these anomolies
            if math.isnan(image_quality):
                continue
            if start_recording and image_quality < float(args.ref_quality):
                file_full_path = saving_img_path + str(image_num) + ".jpg"
                cv2.imwrite(file_full_path, gray,[int(cv2.IMWRITE_JPEG_QUALITY), 100])
                # make sure the image is saved
                while(os.path.getsize(file_full_path) < 1):
                    cv2.imwrite(file_full_path, gray,[int(cv2.IMWRITE_JPEG_QUALITY), 100])
                image_num += 1
                print('%d images saved\r' % (image_num), end="")
            
            # specify the font and draw the key using puttext
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(clone,str(int(image_quality * 10) / 10),(right - img_w, top), font, .8,(255,255,255),2,cv2.LINE_AA)
            cv2.imshow("Gray", gray)

            # draw the segmented hand
            cv2.rectangle(clone, (right, top), (left, bottom), (0,255,0), 2)

            # display the frame with segmented hand
            cv2.imshow("Video Feed", clone)

            # observe the keypress by the user
            keypress = cv2.waitKey(1) & 0xFF

            # if the user pressed "q", then stop looping
            if keypress == ord("q") or image_num > int(args.img_num) - 1:
                break
        
            if keypress == ord("s"):
                start_recording = not start_recording

        else:
            print("[Warning!] Error input, Please check your(camra Or video)")
            break
    # free up memory
    camera.release()
    cv2.destroyAllWindows()
Beispiel #9
0
from libsvm import svmutil  # Trick to fix brisque import error in OSX
from brisque import BRISQUE

import torch

from utils import utils_image as util
from utils import utils_model

from models.network_dncnn import DnCNN as net

## Initiliaze Params ##

# Inference Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Brisq Object
brisq = BRISQUE()

# Model zoo
model_pool = 'model_zoo'


def main(args):

    # Model name
    if args['model'] is None:
        model_name = 'dncnn_50'  # 'dncnn_25' | 'dncnn_50' | 'dncnn_gray_blind' | 'dncnn_color_blind' | 'dncnn3'
    else:
        model_name = args['model']

    # RGB or Gray Scale mode
    if args['color'] == 'rgb':
Beispiel #10
0
            #         plt.suptitle(self.supTitle[idx], fontsize="x-large")
            #         for j in range(6):
            #             if j <= 2:
            #                 ax[0][j].imshow(result[j])
            #                 ax[0][j].axis('off')
            #                 ax[0][j].set_title(self.subTitle[j])
            #             else:
            #                 ax[1][j - 3].imshow(result[j])
            #                 ax[1][j - 3].axis('off')
            #                 ax[1][j - 3].set_title(self.subTitle[j])
            #
            #         mng = plt.get_current_fig_manager()
            #         mng.full_screen_toggle()
            #         if os.path.exists('examples/%s' % self.images[imIdx]) == False:
            #             os.makedirs('examples/%s' % self.images[imIdx])
            #         plt.savefig(os.path.join('examples/%s' % self.images[imIdx], self.supTitle[idx] + '.png'))
            #         figSaveIndex += 1
            #         plt.close()
            toc = time.clock()
            progress += 1
            print('Progress % d / %d with time: % .4f' % (progress, self.sampleNumber[1] - self.sampleNumber[0], toc - tic))
        import dicttoxml
        xl = dicttoxml.dicttoxml(resultDict, attr_type=False)
        f = open("xml/kadis_distortions_fixed_%d_%d.xml" % (self.sampleNumber[0], self.sampleNumber[1]), "wb")
        f.write(xl)
        np.save("npy/kadis_distortions_fixed_%d_%d.npy" % (self.sampleNumber[0], self.sampleNumber[1]), npyData)
        np.save("brisque/kadis_distortions_brisque_%d_%d.npy" % (self.sampleNumber[0], self.sampleNumber[1]), npyBRQ)

brq = BRISQUE()
DG = DistortGenerate()
DG.image_generate()
import glob
from os.path import join

from brisque import BRISQUE

score_calculator = BRISQUE()

path = "/home/zenit/Pictures/Export"
pattern = 'P1000306*.jpg'
full_path = join(path, pattern)

matching_files = glob.glob(full_path)


def calculate_score(image_path):
    score = score_calculator.get_score(image_path)
    return score


file_score_tuples = map(lambda file: (file, calculate_score(file)), matching_files)
max_score_file = max(file_score_tuples, key=lambda item: item[1])
print("max score file is " + max_score_file[0])
Beispiel #12
0
 def __init__(self):
     super().__init__()
     self.name = "brisque_in"
     self.brisque = BRISQUE()
     self.final_score = 0.
Beispiel #13
0
 def __init__(self):
     super().__init__()
     self.name = "brisque_gen"
     self.brisque = BRISQUE()
Beispiel #14
0
 def test_score_from_scaled_feature(self):
     """Test score from scaled feature from Matlab original code."""
     brisque = BRISQUE()
     for idx, scaled_feat in enumerate(self._scaled_feats):
         score = brisque._calculate_score(scaled_feat)
         self.assertAlmostEqual(score, self._expected_score[idx], places=2)