class HumanDetectionAndBlurFilterSample(object):
    """ human detection and blur filter sample """

    def __init__(self):
        """ read config file and initialize auth client """
        with open('./config.json', 'r') as settings:
            config = json.load(settings)
            client_id = config['CLIENT_ID']
            client_secret = config['CLIENT_SECRET']

        vrs_auth_client = AuthClient(client_id, client_secret)
        self.vrs_client = VisualRecognition(vrs_auth_client)

        ips_auth_client = AuthClient(client_id, client_secret)
        self.ips_client = ImageProcessing(ips_auth_client)

    def __detect_humans(self, img_path):
        res = self.vrs_client.detect_humans(img_path)
        return [human['location'] for human in res['humans']]

    def __blur_filter(self, img_path, options, locations):
        parameters = {'locations': locations, 'type': 'blur', 'options': options}
        res = self.ips_client.filter(img_path, parameters)
        return res

    def main(self):
        """ main """
        parser = argparse.ArgumentParser(description='Blur filter sample')
        parser.add_argument('-f', '--file', type=str, dest='file_path', help='specify image file (JPEG or PNG) to process')
        parser.add_argument('--ksize_width', type=int, dest='ksize_width', default=31, help='specify kernel size width')
        parser.add_argument('--ksize_height', type=int, dest='ksize_height', default=31, help='specify kernel size height')

        args = parser.parse_args()
        if args.file_path is None:
            parser.print_help()
            return

        locations = self.__detect_humans(args.file_path)

        options = {
            'locations': {
                'shape': 'min_enclosing_circle',
                'edge': 'blur'
            },
            'ksize_width': args.ksize_width,
            'ksize_height': args.ksize_height,
        }
        res = self.__blur_filter(args.file_path, options, locations)

        if not os.path.exists('./results'):
            os.mkdir('./results')
        with open('./results/human_detection_and_blur_filter.jpg', 'wb') as f:
            f.write(res)
class TestMethodError(TestCase):

    def setUp(self):
        self.aclient = Mock()
        self.aclient.get_access_token = Mock(return_value='atoken')
        self.aclient.get_api_key = Mock(return_value='apikey')
        self.aclient.session = Mock(return_value={'access_token': 'atoken'})
        self.ips = ImageProcessing(self.aclient)
        self.__parameters = {
            'locations': [{'left': 0, 'top': 0, 'right': 1, 'bottom': 1}],
            'type': 'blur',
            'options': {'ksize': 31}
        }

    def test_filter_file_not_found(self):
        with pytest.raises(ValueError) as excinfo:
            self.ips.filter('image.jpg', self.__parameters)
        assert util.RESOURCE_ERROR == str(excinfo.value)

    @mock.patch('json.loads')
    @mock.patch('requests.post')
    def test_filter_resource_not_found(self, req, ret):
        req.return_value.text = 'test'
        req.return_value.status_code = 400
        ret.return_value = {'error': {'code': 'invalid_uri',
                                      'message': 'The requested URI does not represent any resource on the server.'}}
        try:
            self.ips.filter('http://test.com/test.jpg', self.__parameters)
        except ClientError as excinfo:
            assert ret.return_value == excinfo.response
            assert req.return_value.status_code == excinfo.status_code

    @mock.patch('imghdr.what')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.ips.client.open')
    @mock.patch('requests.post')
    def test_filter_gif(self, req, opn, isfile, imghdr):
        req.side_effect = RequestException
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        imghdr.return_value = 'gif'
        with pytest.raises(ValueError) as excinfo:
            self.ips.filter('image.gif', self.__parameters)
        assert util.UNSUPPORTED_ERROR == str(excinfo.value)
class TestMethodOK(TestCase):

    def setUp(self):
        self.aclient = Mock()
        self.aclient.get_access_token = Mock(return_value='atoken')
        self.aclient.get_api_key = Mock(return_value='apikey')
        self.aclient.session = Mock(return_value={'access_token': 'atoken'})
        self.ips = ImageProcessing(self.aclient)
        self.__parameters = {
            'locations': [{'left': 0, 'top': 0, 'right': 1, 'bottom': 1}],
            'type': 'blur',
            'options': {'ksize': 31}
        }
        self.__expected = b'image'

    def test_param_err(self):
        with pytest.raises(TypeError):
            self.ips.filter()

    @mock.patch('requests.post')
    def test_filter_uri(self, req):
        req.return_value.content = self.__expected
        req.return_value.status_code = 200
        assert self.__expected == self.ips.filter('http://test.com/test.jpg', self.__parameters)
        headers = make_headers('application/json')
        payload = json.dumps({'image': 'http://test.com/test.jpg', 'parameters': self.__parameters})
        req.assert_called_once_with(ENDPOINT + '/filter', headers=headers, data=payload)

    @mock.patch('imghdr.what')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.ips.client.open')
    @mock.patch('requests.post')
    def test_filter_jpeg(self, req, opn, isfile, imghdr):
        req.return_value.content = self.__expected
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        imghdr.return_value = 'jpeg'
        assert self.__expected == self.ips.filter('test.jpg', self.__parameters)
        isfile.assert_called_once_with('test.jpg')
        imghdr.assert_called_once_with('test.jpg')
        opn.assert_called_once_with('test.jpg', 'rb')
        headers = make_headers(None)
        files = {'image': ('test.jpg', opn(), 'image/jpeg')}
        data = {'parameters': json.dumps(self.__parameters)}
        req.assert_called_once_with(ENDPOINT + '/filter', headers=headers, files=files, data=data)

    @mock.patch('imghdr.what')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.ips.client.open')
    @mock.patch('requests.post')
    def test_filter_png(self, req, opn, isfile, imghdr):
        req.return_value.content = self.__expected
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        imghdr.return_value = 'png'
        assert self.__expected == self.ips.filter('test.png', self.__parameters)
        isfile.assert_called_once_with('test.png')
        imghdr.assert_called_once_with('test.png')
        opn.assert_called_once_with('test.png', 'rb')
        headers = make_headers(None)
        files = {'image': ('test.png', opn(), 'image/png')}
        data = {'parameters': json.dumps(self.__parameters)}
        req.assert_called_once_with(ENDPOINT + '/filter', headers=headers, files=files, data=data)
Exemplo n.º 4
0
class GaussianFilterSample(object):
    """ gaussian filter sample """
    def __init__(self):
        """ read config file and initialize auth client """
        with open('./config.json', 'r') as settings:
            config = json.load(settings)
            client_id = config['CLIENT_ID']
            client_secret = config['CLIENT_SECRET']

        self.auth_client = AuthClient(client_id, client_secret)
        self.ips_client = ImageProcessing(self.auth_client)

    def main(self):
        """ main """
        parser = argparse.ArgumentParser(description='Gaussian filter sample')
        parser.add_argument('-f',
                            '--file',
                            type=str,
                            dest='file_path',
                            help='specify image file (JPEG or PNG) to process')
        parser.add_argument('-t',
                            '--location_top',
                            type=int,
                            dest='loc_top',
                            help='specify locations top')
        parser.add_argument('-r',
                            '--location_right',
                            type=int,
                            dest='loc_right',
                            help='specify locations right')
        parser.add_argument('-b',
                            '--location_bottom',
                            type=int,
                            dest='loc_bottom',
                            help='specify locations bottom')
        parser.add_argument('-l',
                            '--location_left',
                            type=int,
                            dest='loc_left',
                            help='specify locations left')
        parser.add_argument('--ksize_width',
                            type=int,
                            dest='ksize_width',
                            default=31,
                            help='specify gaussian kernel size width')
        parser.add_argument('--ksize_height',
                            type=int,
                            dest='ksize_height',
                            default=31,
                            help='specify gaussian kernel size height')
        parser.add_argument(
            '--sigma_x',
            type=float,
            dest='sigma_x',
            default=0,
            help='specify Gaussian kernel standard deviation in X direction')
        parser.add_argument(
            '--sigma_y',
            type=float,
            dest='sigma_y',
            default=0,
            help='specify Gaussian kernel standard deviation in Y direction')
        args = parser.parse_args()
        if args.file_path is None \
                or args.loc_left is None \
                or args.loc_top is None \
                or args.loc_right is None \
                or args.loc_bottom is None:
            parser.print_help()
            return

        parameters = {
            'locations': [{
                'left': args.loc_left,
                'top': args.loc_top,
                'right': args.loc_right,
                'bottom': args.loc_bottom
            }],
            'type':
            'gaussian',
            'options': {
                'locations': {
                    'shape': 'min_enclosing_circle',
                    'edge': 'blur'
                },
                'ksize_width': args.ksize_width,
                'ksize_height': args.ksize_height,
                'sigma_x': args.sigma_x,
                'sigma_y': args.sigma_y
            }
        }

        res = self.ips_client.filter(args.file_path, parameters)
        if not os.path.exists('./results'):
            os.mkdir('./results')
        with open('./results/image_filter.jpg', 'wb') as f:
            f.write(res)