Slide Puzzle Python Code Examples

broken image


OpenSlide Python is a Python interface to the OpenSlide library.

Description of 8-Puzzle Problem: The 15-puzzle (also called Gem Puzzle, Boss Puzzle, Game of Fifteen, Mystic Square and many others) is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing. The puzzle also exists in other sizes, particularly the smaller 8-puzzle. Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1. Examples: Input: board = 1,2,3,4,0,5 Output: 1 Explanation: Swap the 0 and the 5 in one move.

OpenSlide is a C library that provides a simple interface for readingwhole-slide images, also known as virtual slides, which are high-resolutionimages used in digital pathology. These images can occupy tens of gigabyteswhen uncompressed, and so cannot be easily read using standard tools orlibraries, which are designed for images that can be comfortablyuncompressed into RAM. Whole-slide images are typically multi-resolution;OpenSlide allows reading a small amount of image data at the resolutionclosest to a desired zoom level.

OpenSlide can read virtual slides in several formats:

  • Aperio (.svs, .tif)

  • Hamamatsu (.ndpi, .vms, .vmu)

  • Leica (.scn)

  • MIRAX (.mrxs)

  • Philips (.tiff)

  • Sakura (.svslide)

  • Trestle (.tif)

  • Ventana (.bif, .tif)

  • Generic tiled TIFF (.tif)

OpenSlide Python is released under the terms of the GNU Lesser GeneralPublic License, version 2.1.

Basic usage¶

OpenSlide objects¶

class openslide.OpenSlide(filename)

An open whole-slide image.

If any operation on the object fails, OpenSlideError is raised.OpenSlide has latching error semantics: once OpenSlideError israised, all future operations on the OpenSlide, other thanclose(), will also raise OpenSlideError.

close() is called automatically when the object is deleted.The object may be used as a context manager, in which case it will beclosed upon exiting the context.

Parameters

filename (str) – the file to open

Raises
  • OpenSlideUnsupportedFormatError – if the file is not recognized byOpenSlide

  • OpenSlideError – if the file is recognized but an error occurred

classmethod detect_format(filename)

Return a string describing the format vendor of the specified file.This string is also accessible via the PROPERTY_NAME_VENDORproperty.

If the file is not recognized, return None.

Parameters

filename (str) – the file to examine

level_count

The number of levels in the slide. Levels are numbered from 0(highest resolution) to level_count-1 (lowest resolution).

dimensions

A (width,height) tuple for level 0 of the slide.

level_dimensions

A list of (width,height) tuples, one for each level of the slide.level_dimensions[k] are the dimensions of level k.

level_downsamples

A list of downsample factors for each level of the slide.level_downsamples[k] is the downsample factor of level k.

properties

Metadata about the slide, in the form of aMapping from OpenSlide property name toproperty value. Property values are always strings. OpenSlideprovides some standard properties, plusadditional properties that vary by slide format.

associated_images

Images, such as label or macro images, which are associated with thisslide. This is a Mapping from imagename to RGBA Image.

Unlike in the C interface, these images are not premultiplied.

read_region(location, level, size)

Return an RGBA Image containing thecontents of the specified region.

Unlike in the C interface, the image data is not premultiplied.

Parameters
  • location (tuple) – (x,y) tuple giving the top left pixel inthe level 0 reference frame

  • level (int) – the level number

  • size (tuple) – (width,height) tuple giving the region size

get_best_level_for_downsample(downsample)

Return the best level for displaying the given downsample.

Parameters

downsample (float) – the desired downsample factor

get_thumbnail(size)

Return an Image containing an RGB thumbnailof the slide.

Parameters

size (tuple) – the maximum size of the thumbnail as a(width,height) tuple

close()

Close the OpenSlide object.

Standard properties¶

The openslide module provides attributes containing the names ofsome commonly-used OpenSlide properties.

openslide.PROPERTY_NAME_COMMENT

The name of the property containing a slide's comment, if any.

openslide.PROPERTY_NAME_VENDOR

The name of the property containing an identification of the vendor.

openslide.PROPERTY_NAME_QUICKHASH1

The name of the property containing the 'quickhash-1' sum.

openslide.PROPERTY_NAME_BACKGROUND_COLOR

The name of the property containing a slide's background color, if any.It is represented as an RGB hex triplet.

openslide.PROPERTY_NAME_OBJECTIVE_POWER

The name of the property containing a slide's objective power, if known.

openslide.PROPERTY_NAME_MPP_X

The name of the property containing the number of microns per pixel inthe X dimension of level 0, if known.

openslide.PROPERTY_NAME_MPP_Y

The name of the property containing the number of microns per pixel inthe Y dimension of level 0, if known.

openslide.PROPERTY_NAME_BOUNDS_X

The name of the property containing the X coordinate of the rectanglebounding the non-empty region of the slide, if available.

openslide.PROPERTY_NAME_BOUNDS_Y

The name of the property containing the Y coordinate of the rectanglebounding the non-empty region of the slide, if available.

openslide.PROPERTY_NAME_BOUNDS_WIDTH

The name of the property containing the width of the rectangle boundingthe non-empty region of the slide, if available.

openslide.PROPERTY_NAME_BOUNDS_HEIGHT

The name of the property containing the height of the rectangle boundingthe non-empty region of the slide, if available.

Exceptions¶

exception openslide.OpenSlideError
Slide Puzzle Python Code Examples

An error produced by the OpenSlide library.

Once OpenSlideError has been raised by a particularOpenSlide, all future operations on that OpenSlide(other than close()) will also raiseOpenSlideError.

exception openslide.OpenSlideUnsupportedFormatError

OpenSlide does not support the requested file. Subclass ofOpenSlideError.

Wrapping a PIL Image¶

class openslide.ImageSlide(file)

A wrapper around an Image object thatprovides an OpenSlide-compatible API.

Parameters

file – a filename or Image object

Raises

IOError – if the file cannot be opened

openslide.open_slide(filename)

Return an OpenSlide for whole-slide images and anImageSlide for other types of images.

Parameters

filename (str) – the file to open

Raises
  • OpenSlideError – if the file is recognized by OpenSlide but anerror occurred

  • IOError – if the file is not recognized at all

Deep Zoom support¶

OpenSlide Python provides functionality for generating individualDeep Zoom tiles from slide objects. This is useful for displayingwhole-slide images in a web browser without converting the entire slide toDeep Zoom or a similar format.

class openslide.deepzoom.DeepZoomGenerator(osr, tile_size=254, overlap=1, limit_bounds=False)

A Deep Zoom generator that wraps anOpenSlide orImageSlide object.

Parameters
  • osr – the slide object

  • tile_size (int) – the width and height of a single tile. For bestviewer performance, tile_size+2*overlap should be a power of two.

  • overlap (int) – the number of extra pixels to add to each interior edgeof a tile

  • limit_bounds (bool) – True to render only the non-empty slideregion

Pdf

An error produced by the OpenSlide library.

Once OpenSlideError has been raised by a particularOpenSlide, all future operations on that OpenSlide(other than close()) will also raiseOpenSlideError.

exception openslide.OpenSlideUnsupportedFormatError

OpenSlide does not support the requested file. Subclass ofOpenSlideError.

Wrapping a PIL Image¶

class openslide.ImageSlide(file)

A wrapper around an Image object thatprovides an OpenSlide-compatible API.

Parameters

file – a filename or Image object

Raises

IOError – if the file cannot be opened

openslide.open_slide(filename)

Return an OpenSlide for whole-slide images and anImageSlide for other types of images.

Parameters

filename (str) – the file to open

Raises
  • OpenSlideError – if the file is recognized by OpenSlide but anerror occurred

  • IOError – if the file is not recognized at all

Deep Zoom support¶

OpenSlide Python provides functionality for generating individualDeep Zoom tiles from slide objects. This is useful for displayingwhole-slide images in a web browser without converting the entire slide toDeep Zoom or a similar format.

class openslide.deepzoom.DeepZoomGenerator(osr, tile_size=254, overlap=1, limit_bounds=False)

A Deep Zoom generator that wraps anOpenSlide orImageSlide object.

Parameters
  • osr – the slide object

  • tile_size (int) – the width and height of a single tile. For bestviewer performance, tile_size+2*overlap should be a power of two.

  • overlap (int) – the number of extra pixels to add to each interior edgeof a tile

  • limit_bounds (bool) – True to render only the non-empty slideregion

level_count

The number of Deep Zoom levels in the image.

tile_count

The total number of Deep Zoom tiles in the image.

level_tiles

A list of (tiles_x,tiles_y) tuples for each Deep Zoom level.level_tiles[k] are the tile counts of level k.

level_dimensions

A list of (pixels_x,pixels_y) tuples for each Deep Zoom level.level_dimensions[k] are the dimensions of level k.

get_dzi(format)

Return a string containing the XML metadata for the Deep Zoom .dzifile.

Parameters

format (str) – the delivery format of the individual tiles(png or jpeg)

get_tile(level, address)

Return an RGB Image for a tile.

Parameters
  • level (int) – the Deep Zoom level

  • address (tuple) – the address of the tile within the level as a(column,row) tuple

get_tile_coordinates(level, address)

Return the OpenSlide.read_region() arguments corresponding to thespecified tile.

Most applications should use get_tile() instead.

Parameters
  • level (int) – the Deep Zoom level

  • address (tuple) – the address of the tile within the level as a(column,row) tuple

get_tile_dimensions(level, address)

Return a (pixels_x,pixels_y) tuple for the specified tile.

Parameters
  • level (int) – the Deep Zoom level

  • address (tuple) – the address of the tile within the level as a(column,row) tuple

Example programs¶

Several Deep Zoom examples are included with OpenSlide Python:

deepzoom_server.py

A basic server for a single slide. It serves a web page with a zoomableslide viewer, a list of slide properties, and the ability to viewassociated images.

deepzoom_multiserver.py

A basic server for a directory tree of slides. It serves an index pagewhich links to zoomable slide viewers for all slides in the tree.

deepzoom_tile.py

A program to generate and store a complete Deep Zoom directory tree for aslide. It can optionally store an HTML page with a zoomable slide viewer,a list of slide properties, and the ability to view associated images.

Python Powerpoint Slides

This program is intended as an example. If you need to generate Deep Zoomtrees for production applications, consider using VIPS instead.

This page contains all Python scripts that we have posted our site so far.

Examples

pywhois is a Python module for retrieving WHOIS information of domains. pywhois works with Python 2.4+ and no external dependencies [Source]

In this script I'm using 8 possible answers, but please feel free to add more as you wish. There are 20 answers inside the Magic 8 Ball, and you can find them all here.

A common first step when you want to use a Web-based services is to see if they have an API. Luckily for me, Commandlinefu.com provides one and can be found here

In an earlier post 'OS.walk in Python', I described how to use os.walk and showed some examples on how to use it in scripts. In this article, I will show how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.

This post will show how you can make a small and easy-to-use port scanner program written in Python.

Backup all MySQL databases, one in each file with a timestamp on the end using ConfigParser.

To make a request to the Web search API, we have to import the modules that we
need.

Pxssh is based on pexpect. It's class extends pexpect.spawn to specialize setting up SSH connections.

This script can be used to parse date and time.

Bitly allows users to shorten, share, and track links (URLs). It's a way to save, share and discover links on the web.

The smtplib module defines an SMTP client session object that can be used to send
mail to any Internet machine with an SMTP or ESMTP listener daemon. SMTP stands for Simple Mail Transfer Protocol.

This short script uses the os.listdir function (that belongs to the OS module) to search through a given path ('.') for all files that endswith '.txt'.

Speedtest.net is a connection analysis website where users can test their internet
speed against hundreds of geographically dispersed servers around the world.

In this article, I will show how to use the os.walk() module function to walk a
directory tree, and the fnmatch module for matching file names.

Knowing how to parse JSON objects is useful when you want to access an API
from various web services that gives the response in JSON.

Time for a script again, this one will geolocate an IP address based on input from the user. For this script, we will be using a bunch of Python modules to accomplish this.

This script will ask the user for its username, by using the raw_input function. Then a list of allowed users is created named user1 and user2. The control statement checks if the input from the user matches the ones that are in the allowed users list.

This script will use the Twitter API to search for tweets.

In this post, I will show you how you can do it without that by just using
datetime.datetime.now() .

The second part of the post is about the the timedelta class, in which we can see
the difference between two date, time, or datetime instances to microsecond
resolution.

This is a classic 'roll the dice' program.

This small script will count the number of hits in a Apache/Nginx log file.

This script will show all entries in the file that is specified in the log file
variable.

In this post, I will show you how you can print out the dates and times by just using datetime.datetime.now().

This small program extends the previous guessing game I wrote about in this
: post 'Guessing Game'.

This script is an interactive guessing game, which will ask the user to guess a
number between 1 and 99.

You can use Pythons string and random modules to generate passwords.

OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up.

This script converts speed from KM/H to MPH, which may be handy for calculating
speed limits when driving abroad, especially for UK and US drivers.

In this script, we are going to use the re module to get all links from any website.

This script converts temperature between Fahrenheit to Celsius.

Additional Resources

In this post we will be looking on how to use the Vimeo API in Python.

This program will show how we can use the API to retrieve feeds from YouTube.

This script will calculate the average of three values.

Slide Puzzle Python Code Examples For Beginners

This is a simple Python script to check which external IP address you have.

This is a Python script of the classic game 'Hangman'.

This script will ask for a movie title and a year and then query IMDB for it.

Python code examples

Slide Puzzle Python Code Examples

Here we link to other sites that provides Python code examples.

Recommended Python Training

For Python training, our top recommendation is DataCamp.





broken image