예제 #1
0
    def _load_image(self, img, resize=None):
        """
        Loads an image as a :epkg:`numpy:array`.

        @param      img         image
        @param      resize      resize the image before predicting,
                                see @see me _new_size
        @return                 :epkg:`numpy:array`
        """
        if isinstance(img, str):
            # Loads the image.
            if not os.path.exists(img):
                raise FileNotFoundError(img)
            if resize is None:
                feat = skimage.io.imread(img)
            else:
                pilimg = Image.open(img)
                si = DLImageSegmentation._new_size(pilimg.size, resize)
                pilimg2 = pilimg.resize(si)
                feat = pil_to_ndarray(pilimg2)
        elif isinstance(img, numpy.ndarray):
            if resize is None:
                feat = img
            else:
                # Does not work...
                # feat = skimage.transform.resize(img, resize)
                # So...
                pilimg = Image.fromarray(img).convert('RGB')
                pilimg2 = pilimg.resize(resize)
                feat = pil_to_ndarray(pilimg)
        else:
            raise NotImplementedError("Not implemented for type '{0}'".format(
                type(img)))
        return feat
예제 #2
0
def test_imexport_imimport():
    shape = (2, 2)
    image = np.zeros(shape)
    with expected_warnings(['precision loss']):
        pil_image = ndarray_to_pil(image)
    out = pil_to_ndarray(pil_image)
    assert out.shape == shape
예제 #3
0
def alternative_prepare_image(image):
    if str(type(image)) == "<class 'PIL.Image.Image'>":
      image = pil_to_ndarray(image)
    ndar = image.reshape(SRC_H, SRC_W, SRC_D)
    im = Image.fromarray(ndar)
    im = im.resize((IMG_W, IMG_H))
    im_arr = np.frombuffer(im.tobytes(), dtype=np.uint8) # in object exposing buffer interface out ndarray
    im_arr = im_arr.reshape((IMG_H, IMG_W, IMG_D)) # 200, 66, 3
예제 #4
0
파일: batt.py 프로젝트: leegggg/towerdef
def checkSsim(cap: PILImg, tpl: PILImg, loc):
    box = (int(loc[0] * tpl.size[0]), int(loc[1] * tpl.size[1]),
           int(loc[2] * tpl.size[0]), int(loc[3] * tpl.size[1]))

    size = tpl.size
    cap = cap.resize(size).crop(box).convert("L")
    tpl = tpl.resize(size).crop(box).convert("L")

    # for very small window
    size = tpl.size
    while size[0] < 20 or size[1] < 20:
        size = (size[0] * 2, size[1] * 2)

    cap = cap.resize(size)
    tpl = tpl.resize(size)
    # cap.show()
    # tpl.show()
    likeness = ssim(pil_plugin.pil_to_ndarray(cap),
                    pil_plugin.pil_to_ndarray(tpl))
    return likeness
예제 #5
0
def load_img_from_url(photo_url):
    if not isinstance(photo_url, str):
        raise ValueError("Photo_url parameter expected to be string.")

    if photo_url.startswith("http://"):
        photo_url = "http://" + urllib.parse.quote(photo_url)[9:]
    elif photo_url.startswith("https://"):
        photo_url = "https://" + urllib.parse.quote(photo_url)[10:]
    else:
        raise ValueError("Unknown url protocol!")

    response = requests.get(photo_url, stream=True)
    response.raw.decode_content = True
    image = Image.open(response.raw)
    npimage = pil_to_ndarray(image)

    return npimage
예제 #6
0
    def test_blur(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")
        temp = get_temp_folder(__file__, "temp_blur")
        img = os.path.join(temp, '..', 'data', 'img1.jpg')

        pil_img = Image.open(img)
        skimg = pil_to_ndarray(pil_img)
        im1 = skimg.copy().ravel()
        blur(skimg, (10, 20), (100, 200))
        im2 = skimg.copy().ravel()
        self.assertTrue(im1.tolist() != im2.tolist())
        pil_img2 = Image.fromarray(skimg)
        dest = os.path.join(temp, "img_blur.jpg")
        pil_img2.save(dest)
예제 #7
0
 def _binarize(
     cls, images: List[bytes],
     method: Callable[[numpy.ndarray],
                      numpy.ndarray]) -> (List[bytes], str):
     out_path = cls._get_random_name()
     out: List[bytes] = []
     count = 1
     for image_bytes in images:
         buf = BytesIO(image_bytes)
         im = pim.open(buf)
         image = Image(pil_to_ndarray(im))
         grayscale = rgb2gray(image)
         # thresh: numpy.ndarray = method(grayscale)
         # binary: numpy.ndarray = grayscale > thresh
         img_bytes: bytes = cls._binary_image_to_bytes(grayscale)
         with open(os.path.join(out_path, f"_{count}.jpg"), "wb") as f:
             f.write(img_bytes)
         out.append(img_bytes)
         buf.close()
         count += 1
     return out, out_path
예제 #8
0
def prepare_image(img):

    # ORIGINAL
    # if(type(img) == wx._core.Bitmap):
    #     img.CopyToBuffer(Screenshot.image_array) # img = pixel data
    #     img = np.frombuffer(Screenshot.image_array, dtype=np.uint8) # in object exposing buffer interface out ndarray
    # img = img.reshape(Screenshot.SRC_H, Screenshot.SRC_W, Screenshot.SRC_D)
    # im = Image.fromarray(img)
    # im = im.resize((Screenshot.IMG_W, Screenshot.IMG_H))
    # im_arr = np.frombuffer(im.tobytes(), dtype=np.uint8) # in object exposing buffer interface out ndarray
    # im_arr = im_arr.reshape((Screenshot.IMG_H, Screenshot.IMG_W, Screenshot.IMG_D)) # 200, 66, 3
    # return img_as_float(im_arr) # in ndarray out ndarray of float64

    # ALTERNATIVE
    if str(type(img)) == "<class 'PIL.Image.Image'>":
        img = img.resize((Screenshot.IMG_W, Screenshot.IMG_H))  # 200, 66
    else:
        img = img.reshape(Screenshot.SRC_H, Screenshot.SRC_W, Screenshot.SRC_D)
        img = Image.fromarray(img)
        img = img.resize((Screenshot.IMG_W, Screenshot.IMG_H))
    im_arr = pil_to_ndarray(img)
    return img_as_float(
        im_arr)  # in ndarray out ndarray of float64 # shape is unchanged
예제 #9
0
 def roundtrip_pil_image(self, x):
     pil_image = ndarray_to_pil(x)
     y = pil_to_ndarray(pil_image)
     return y
예제 #10
0
def test_imexport_imimport():
    shape = (2, 2)
    image = np.zeros(shape)
    pil_image = ndarray_to_pil(image)
    out = pil_to_ndarray(pil_image)
    assert out.shape == shape
예제 #11
0
def test_imexport_imimport():
    shape = (2, 2)
    image = np.zeros(shape)
    pil_image = ndarray_to_pil(image)
    out = pil_to_ndarray(pil_image)
    assert out.shape == shape
예제 #12
0
 def roundtrip_pil_image(self, x):
     pil_image = ndarray_to_pil(x)
     y = pil_to_ndarray(pil_image)
     return y
예제 #13
0
draw.text((10, 10),"This Homework is cooly cool",(255), font=font)
draw.text((10, 35),"This Homework is cooly cool",(255), font=font)
draw.text((10, 60),"This Homework is cooly cool",(255), font=font)
draw.text((10, 85),"This Homework is cooly cool",(255), font=font)
draw.text((10, 110),"This Homework is cooly cool",(255), font=font)
draw.text((10, 135),"This Homework is cooly cool",(255), font=font)
draw.text((10, 160),"This Homework is cooly cool",(255), font=font)
draw.text((10, 185),"This Homework is cooly cool",(255), font=font)
draw.text((10, 210),"This Homework is cooly cool",(255), font=font)
draw.text((10, 235),"This Homework is cooly cool",(255), font=font)
draw.text((10, 260),"This Homework is cooly cool",(255), font=font)
y_test_missing.save('y_test_missing.png')

#Building and saving the mask
mask = ImageChops.difference(y_test_missing, y_test)
mask = np.array(pil_to_ndarray(mask) <= 0.1, dtype=int)
mask_img = mask * 255
mask = ndarray_to_pil(mask)
mask_img = ndarray_to_pil(mask_img)
mask_img.save('mask.png', 'PNG')


psnr_y_test_y_test_missing = peak_signal_noise_ratio(pil_to_ndarray(y_test), pil_to_ndarray(y_test_missing))
ssim_y_test_y_test_missing = structural_similarity(pil_to_ndarray(y_test), pil_to_ndarray(y_test_missing))
print(psnr_y_test_y_test_missing)
print(ssim_y_test_y_test_missing)
print('\n')

"""
plt.imshow(y_train, cmap='gray')
plt.show()
예제 #14
0
def video_image(image_or_file,
                duration=None,
                zoom=None,
                opacity=None,
                **kwargs):
    """
    Creates a :epkg:`ImageClip`.
    Créé une vidéo à partir d'une image.

    @param      image_or_file   image or file
    @param      duration        duration or None if not known
    @param      zoom            applies a zoom on the image
    @param      opacity         opacity of the image (0 for transparent, 255 for opaque)
    @param      kwargs          additional parameters for :epkg:`ImageClip`
    @return                     :epkg:`ImageClip`

    If *duration* is None, it will be fixed when the image is
    composed with another one. The image remains wherever it is placed.
    """
    if isinstance(image_or_file, str):
        img = Image.open(image_or_file)
        return video_image(img,
                           duration=duration,
                           zoom=zoom,
                           opacity=opacity,
                           **kwargs)
    elif isinstance(image_or_file, numpy.ndarray):
        if zoom is not None:
            from skimage.transform import rescale
            img = rescale(image_or_file, zoom)
            return video_image(img,
                               duration=duration,
                               opacity=opacity,
                               **kwargs)
        else:
            img = image_or_file
            if len(img.shape) != 3:
                raise ValueError("Image is not RGB or RGBA shape={0}".format(
                    img.shape))
            if img.shape[2] == 3:
                from skimage.io._plugins.pil_plugin import pil_to_ndarray
                pilimg = Image.fromarray(img).convert('RGBA')
                img = pil_to_ndarray(pilimg)
                if opacity is None:
                    opacity = 255
            if isinstance(opacity, int):
                img[:, :, 3] = opacity
            elif isinstance(opacity, float):
                img[:, :, 3] = int(opacity * 255)
            elif opacity is not None:
                raise TypeError("opacity should be int or float or None")
            return ImageClip(img,
                             duration=duration,
                             transparent=True,
                             **kwargs)
    elif isinstance(image_or_file, Image.Image):
        from skimage.io._plugins.pil_plugin import pil_to_ndarray
        if image_or_file.mode != 'RGBA':
            image_or_file = image_or_file.convert('RGBA')
        if zoom is not None:
            image_or_file = image_or_file.resize(zoom)
        img = pil_to_ndarray(image_or_file)
        return video_image(img, duration=duration, opacity=opacity, **kwargs)
    else:
        raise TypeError("Unable to create a video from type {0}".format(
            type(image_or_file)))
예제 #15
0
import numpy as np

log = logging.getLogger(__name__)

if __name__ == '__main__':

    logging.basicConfig(level=logging.INFO)

    filename = "data/raw/Tobias_Schoch_TOS_kopf_big_2.jpg"

    input_file = pathlib.Path(filename)

    img = prepare_image(filename)

    img = img.resize((400, 400), Image.ANTIALIAS)
    img = pil_to_ndarray(img)

    print(skimage.io.available_plugins)

    size = img.shape[:2]
    size = np.array(size)
    N = 256
    thread_color = 0.2

    nodes = node_positions(N, np.min(size) / 2, size / 2)
    nodes[:, 0] = np.clip(nodes[:, 0], 0, size[0] - 1)
    nodes[:, 1] = np.clip(nodes[:, 1], 0, size[1] - 1)

    state = np.zeros_like(img, dtype=img.dtype)
    state[:] = 255