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)
Exemplo n.º 2
0
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.vrs = VisualRecognition(self.aclient)
        self.__hd_expected = {
            'humans': [{
                'score': 1,
                'location': {
                    'top': 100,
                    'right': 200,
                    'bottom': 200,
                    'left': 100
                }
            }]
        }
        self.__fd_expected = {
            'faces': [{
                'direction': 'left',
                'location': {
                    'top': 100,
                    'right': 200,
                    'bottom': 200,
                    'left': 100
                }
            }]
        }
        self.__fr_expected = {
            "score": 0.787753701210022,
            "source": {
                "location": {
                    "left": 1085,
                    "top": 244,
                    "right": 1307,
                    "bottom": 466
                }
            },
            "target": {
                "location": {
                    "left": 659,
                    "top": 207,
                    "right": 812,
                    "bottom": 360
                }
            }
        }

    def test_param_err(self):
        with pytest.raises(TypeError):
            self.vrs.detect_faces()

    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_faces_uri(self, req):
        req.return_value.text = json.dumps(self.__fd_expected)
        req.return_value.status_code = 200
        assert self.__fd_expected == self.vrs.detect_faces(
            'http://test.com/test.jpg')
        headers = make_headers('application/json')
        payload = json.dumps({'image': 'http://test.com/test.jpg'})
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/detect_faces',
                                    headers=headers,
                                    data=payload)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_faces_jpeg(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__fd_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'jpeg'
        pil_open.return_value = img
        assert self.__fd_expected == self.vrs.detect_faces('test.jpg')
        isfile.assert_called_once_with('test.jpg')
        pil_open.assert_called_once_with('test.jpg')
        opn.assert_called_once_with('test.jpg', 'rb')
        headers = make_headers('image/jpeg')
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/detect_faces',
                                    headers=headers,
                                    data=opn())

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_faces_png(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__fd_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'png'
        pil_open.return_value = img
        assert self.__fd_expected == self.vrs.detect_faces('test.png')
        isfile.assert_called_once_with('test.png')
        pil_open.assert_called_once_with('test.png')
        opn.assert_called_once_with('test.png', 'rb')
        headers = make_headers('image/png')
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/detect_faces',
                                    headers=headers,
                                    data=opn())

    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_humans_uri(self, req):
        req.return_value.text = json.dumps(self.__hd_expected)
        req.return_value.status_code = 200
        assert self.__hd_expected == self.vrs.detect_humans(
            'http://test.com/test.jpg')
        headers = make_headers('application/json')
        payload = json.dumps({'image': 'http://test.com/test.jpg'})
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/detect_humans',
                                    headers=headers,
                                    data=payload)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_humans_jpeg(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__hd_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'jpeg'
        pil_open.return_value = img
        assert self.__hd_expected == self.vrs.detect_humans('test.jpg')
        isfile.assert_called_once_with('test.jpg')
        pil_open.assert_called_once_with('test.jpg')
        opn.assert_called_once_with('test.jpg', 'rb')
        headers = make_headers('image/jpeg')
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/detect_humans',
                                    headers=headers,
                                    data=opn())

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_humans_png(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__hd_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'png'
        pil_open.return_value = img
        assert self.__hd_expected == self.vrs.detect_humans('test.png')
        isfile.assert_called_once_with('test.png')
        pil_open.assert_called_once_with('test.png')
        opn.assert_called_once_with('test.png', 'rb')
        headers = make_headers('image/png')
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/detect_humans',
                                    headers=headers,
                                    data=opn())

    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_compare_faces_uri(self, req):
        req.return_value.text = json.dumps(self.__fr_expected)
        req.return_value.status_code = 200
        assert self.__fr_expected == self.vrs.compare_faces(
            'http://test.com/test_1.jpg', 'http://test.com/test_2.jpg')
        headers = make_headers('application/json')
        payload = json.dumps({
            'source': 'http://test.com/test_1.jpg',
            'target': 'http://test.com/test_2.jpg'
        })
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/compare_faces',
                                    headers=headers,
                                    data=payload)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_compare_faces_jpeg_jpeg(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__fr_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.side_effect = ['jpeg', 'jpeg']
        pil_open.return_value = img
        assert self.__fr_expected == self.vrs.compare_faces(
            'test_1.jpg', 'test_2.jpg')
        headers = {'Authorization': 'Bearer atoken', 'x-api-key': 'apikey'}
        payload = {'source': opn(), 'target': opn()}
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/compare_faces',
                                    headers=headers,
                                    files=payload)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_compare_faces_png_png(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__fr_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.side_effect = ['png', 'png']
        pil_open.return_value = img
        assert self.__fr_expected == self.vrs.compare_faces(
            'test_1.png', 'test_2.png')
        headers = {'Authorization': 'Bearer atoken', 'x-api-key': 'apikey'}
        payload = {'source': opn(), 'target': opn()}
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/compare_faces',
                                    headers=headers,
                                    files=payload)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_compare_faces_jpeg_png(self, req, opn, isfile, pil_open):
        req.return_value.text = json.dumps(self.__fr_expected)
        req.return_value.status_code = 200
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.side_effect = ['jpeg', 'png']
        pil_open.return_value = img
        assert self.__fr_expected == self.vrs.compare_faces(
            'test_1.jpeg', 'test_2.png')
        headers = {'Authorization': 'Bearer atoken', 'x-api-key': 'apikey'}
        payload = {'source': opn(), 'target': opn()}
        req.assert_called_once_with('POST',
                                    ENDPOINT + '/compare_faces',
                                    headers=headers,
                                    files=payload)
Exemplo n.º 3
0
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.vrs = VisualRecognition(self.aclient)

    def test_detect_humans_file_not_found(self):
        with pytest.raises(ValueError) as excinfo:
            self.vrs.detect_humans('image.jpg')
        assert util.RESOURCE_ERROR == str(excinfo.value)

    def test_detect_faces_file_not_found(self):
        with pytest.raises(ValueError) as excinfo:
            self.vrs.detect_faces('image.jpg')
        assert util.RESOURCE_ERROR == str(excinfo.value)

    def test_compare_faces_file_not_found(self):
        with pytest.raises(ValueError) as excinfo:
            self.vrs.compare_faces('image_1.jpg', 'image_2.jpg')
        assert util.RESOURCE_ERROR == str(excinfo.value)

    @mock.patch('json.loads')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_humans_resource_not_found(self, req, ret):
        req.return_value.text = 'test'
        req.return_value.status_code = 404
        ret.return_value = {
            'error': {
                'code': 'resource_not_found',
                'message': 'The specified resource does not exist.'
            }
        }
        try:
            self.vrs.detect_humans('http://test.com/test.jpg')
        except ClientError as excinfo:
            assert ret.return_value == excinfo.response
            assert req.return_value.status_code == excinfo.status_code

    @mock.patch('json.loads')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_faces_resource_not_found(self, req, ret):
        req.return_value.text = 'test'
        req.return_value.status_code = 404
        ret.return_value = {
            'error': {
                'code': 'resource_not_found',
                'message': 'The specified resource does not exist.'
            }
        }
        try:
            self.vrs.detect_faces('http://test.com/test.jpg')
        except ClientError as excinfo:
            assert ret.return_value == excinfo.response
            assert req.return_value.status_code == excinfo.status_code

    @mock.patch('json.loads')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_compare_faces_resource_not_found(self, req, ret):
        req.return_value.text = 'test'
        req.return_value.status_code = 404
        ret.return_value = {
            'error': {
                'code': 'resource_not_found',
                'message': 'The specified resource does not exist.'
            }
        }
        try:
            self.vrs.compare_faces('http://test.com/test_1.jpg',
                                   'http://test.com/test_2.jpg')
        except ClientError as excinfo:
            assert ret.return_value == excinfo.response
            assert req.return_value.status_code == excinfo.status_code

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_humans_gif(self, req, opn, isfile, pil_open):
        req.side_effect = RequestException
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'gif'
        pil_open.return_value = img
        with pytest.raises(ValueError) as excinfo:
            self.vrs.detect_humans('image.gif')
        assert util.UNSUPPORTED_ERROR == str(excinfo.value)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_detect_faces_gif(self, req, opn, isfile, pil_open):
        req.side_effect = RequestException
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'gif'
        pil_open.return_value = img
        with pytest.raises(ValueError) as excinfo:
            self.vrs.detect_faces('image.gif')
        assert util.UNSUPPORTED_ERROR == str(excinfo.value)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    @mock.patch('ricohcloudsdk.vrs.util.SESSION.request')
    def test_compare_faces_gif(self, req, opn, isfile, pil_open):
        req.side_effect = RequestException
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.return_value = True
        img = MagicMock()
        img.format.lower.return_value = 'gif'
        pil_open.return_value = img
        with pytest.raises(ValueError) as excinfo:
            self.vrs.compare_faces('image_1.gif', 'image_2.gif')
        assert util.UNSUPPORTED_ERROR == str(excinfo.value)

    @mock.patch('ricohcloudsdk.vrs.util.Image.open')
    @mock.patch('os.path.isfile')
    @mock.patch('ricohcloudsdk.vrs.client.open')
    def test_compare_faces_jpeg_uri(self, opn, isfile, pil_open):
        opn.side_effect = mock.mock_open()
        opn.read_data = b'readdata'
        isfile.side_effect = [True, False]
        img = MagicMock()
        img.format.lower.return_value = 'jpeg'
        pil_open.return_value = img
        with pytest.raises(ValueError) as excinfo:
            self.vrs.compare_faces('test_1.jpeg', 'https://test.co,/test.jpg')
        assert util.COMBINATION_ERROR == str(excinfo.value)