def visualize_matches(image_left, image_right, points_src, points_dst, match_indexes, title="Associated Features"): if type(points_src) is list: points_src = pyboof.p2b_list_point2D(points_src, np.double) if type(points_dst) is list: points_dst = pyboof.p2b_list_point2D(points_dst, np.double) if type(match_indexes) is list: raise Exception( "Haven't bothered to implement python to java conversion for match_indexes yet" ) # If possible, convert images into a BufferedImage data type if jg.is_instance_of(gateway, image_left, gateway.jvm.boofcv.struct.image.ImageBase): image_left = gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo( image_left, None, True) if jg.is_instance_of(gateway, image_right, gateway.jvm.boofcv.struct.image.ImageBase): image_right = gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo( image_right, None, True) panel = gateway.jvm.boofcv.gui.feature.AssociationPanel(20) panel.setImages(image_left, image_right) panel.setAssociation(points_src, points_dst, match_indexes) gateway.jvm.boofcv.gui.image.ShowImages.showWindow(panel, title)
def union(self, *dstreams: "DStream[T]") -> "DStream[T]": """ Create a unified DStream from multiple DStreams of the same type and same slide duration. """ if not dstreams: raise ValueError("should have at least one DStream to union") if len(dstreams) == 1: return dstreams[0] if len(set(s._jrdd_deserializer for s in dstreams)) > 1: raise ValueError("All DStreams should have same serializer") if len(set(s._slideDuration for s in dstreams)) > 1: raise ValueError("All DStreams should have same slide duration") assert SparkContext._jvm is not None jdstream_cls = SparkContext._jvm.org.apache.spark.streaming.api.java.JavaDStream jpair_dstream_cls = SparkContext._jvm.org.apache.spark.streaming.api.java.JavaPairDStream gw = SparkContext._gateway if is_instance_of(gw, dstreams[0]._jdstream, jdstream_cls): cls = jdstream_cls elif is_instance_of(gw, dstreams[0]._jdstream, jpair_dstream_cls): cls = jpair_dstream_cls else: cls_name = dstreams[0]._jdstream.getClass().getCanonicalName() raise TypeError("Unsupported Java DStream class %s" % cls_name) assert gw is not None jdstreams = gw.new_array(cls, len(dstreams)) for i in range(0, len(dstreams)): jdstreams[i] = dstreams[i]._jdstream return DStream( self._jssc.union(jdstreams), self, dstreams[0]._jrdd_deserializer, )
def _convert_value(self, val: Any, field_name: str) -> Optional[str]: """ Converts the given value into a SQL string. """ from pyspark import SparkContext from pyspark.sql import Column, DataFrame if isinstance(val, Column): assert SparkContext._gateway is not None gw = SparkContext._gateway jexpr = val._jc.expr() if is_instance_of( gw, jexpr, "org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute" ) or is_instance_of( gw, jexpr, "org.apache.spark.sql.catalyst.expressions.AttributeReference" ): return jexpr.sql() else: raise ValueError( "%s in %s should be a plain column reference such as `df.col` " "or `col('column')`" % (val, field_name) ) elif isinstance(val, DataFrame): for df, n in self._temp_views: if df is val: return n df_name = "_pyspark_%s" % str(uuid.uuid4()).replace("-", "") self._temp_views.append((val, df_name)) val.createOrReplaceTempView(df_name) return df_name elif isinstance(val, str): return lit(val)._jc.expr().sql() # for escaped characters. else: return val
def testErrorInPythonCallback(self): with clientserver_example_app_process(): client_server = ClientServer( JavaParameters(), PythonParameters( propagate_java_exceptions=True)) example = client_server.entry_point.getNewExample() try: example.callHello(IHelloFailingImpl( ValueError('My interesting Python exception'))) self.fail() except Py4JJavaError as e: self.assertTrue(is_instance_of( client_server, e.java_exception, 'py4j.Py4JException')) self.assertIn('interesting Python exception', str(e)) try: example.callHello(IHelloFailingImpl( Py4JJavaError( '', client_server.jvm.java.lang.IllegalStateException( 'My IllegalStateException')))) self.fail() except Py4JJavaError as e: self.assertTrue(is_instance_of( client_server, e.java_exception, 'java.lang.IllegalStateException')) client_server.shutdown()
def getParamRanges(self): paramSpecs = self.__bridge.getParamList(self.__session, self.__path).getParamSpecs() paramRanges = [] ##Using some bsearch code here thanks to Forrest Stonedahl and the NetLogo team for paramSpec in paramSpecs: paramRange = [] if (jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.DoubleDiscreteSpec") | jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.DoubleContinuousSpec")): count = paramSpec.choiceCount() val_min = paramSpec.getValueFromChoice(0, count) val_max = paramSpec.getValueFromChoice(count - 1, count) step = (val_max - val_min) / (count - 1) paramRange = [val_min, step, val_max] if jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.CategoricalSpec"): count = paramSpec.choiceCount() paramRange = [] for choice in range(0, count): paramRange.append( paramSpec.getValueFromChoice(choice, count)) if jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.ConstantSpec"): paramRange = [paramSpec.getValueFromChoice(0, 1)] paramRanges.append(paramRange) return paramRanges
def setParamsRandom(self): paramSpecs = self.__bridge.getParamList(self.__session, self.__path).getParamSpecs() ##Using some bsearch code here thanks to Forrest Stonedahl and the NetLogo team for paramSpec in paramSpecs: if jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.DoubleDiscreteSpec"): paramValue = paramSpec.generateRandomValue( self.__gateway.jvm.org.nlogo.api.MersenneTwisterFast()) if jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.DoubleContinuousSpec"): paramValue = paramSpec.generateRandomValue( self.__gateway.jvm.org.nlogo.api.MersenneTwisterFast()) if jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.CategoricalSpec"): paramValue = paramSpec.generateRandomValue( self.__gateway.jvm.org.nlogo.api.MersenneTwisterFast()) if type(paramValue) != bool: #isinstance(data[i][k], bool) paramValue = '"{}"'.format( paramSpec.generateRandomValue( self.__gateway.jvm.org.nlogo.api. MersenneTwisterFast())) if jg.is_instance_of(self.__gateway, paramSpec, "bsearch.space.ConstantSpec"): paramValue = paramSpec.generateRandomValue( self.__gateway.jvm.org.nlogo.api.MersenneTwisterFast()) print("NetLogo command: set " + str(paramSpec.getParameterName()) + " " + str(paramValue)) self.__bridge.command( self.__session, "set " + str(paramSpec.getParameterName()) + " " + str(paramValue))
def set_params_random(self): ''' Sets the parameters randomly through the JavaGateway using Random parameter initialization code from BehaviorSearch ''' paramSpecs = self.app.getParamList(self.path).getParamSpecs() ##Using some bsearch code here thanks to Forrest Stonedahl for paramSpec in paramSpecs: if jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.DoubleDiscreteSpec'): paramValue = paramSpec.generateRandomValue( self.gateway.jvm.org.nlogo.api.MersenneTwisterFast()) if jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.DoubleContinuousSpec'): paramValue = paramSpec.generateRandomValue( self.gateway.jvm.org.nlogo.api.MersenneTwisterFast()) if jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.CategoricalSpec'): paramValue = paramSpec.generateRandomValue( self.gateway.jvm.org.nlogo.api.MersenneTwisterFast()) if type(paramValue) != bool: #isinstance(data[i][k], bool) paramValue = '"{}"'.format( paramSpec.generateRandomValue( self.gateway.jvm.org.nlogo.api.MersenneTwisterFast( ))) if jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.ConstantSpec'): paramValue = paramSpec.generateRandomValue( self.gateway.jvm.org.nlogo.api.MersenneTwisterFast()) print('NetLogo command: set ' + str(paramSpec.getParameterName()) + ' ' + str(paramValue)) self.app.command('set ' + str(paramSpec.getParameterName()) + ' ' + str(paramValue))
def get_param_ranges(self) -> List[List[Union[str, int, float]]]: ''' Returns the parameter ranges ''' paramSpecs = self.app.getParamList(self.path).getParamSpecs() paramRanges = [] ##Using some bsearch code here thanks to Forrest Stonedahl for paramSpec in paramSpecs: paramRange = [] if (jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.DoubleDiscreteSpec') | jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.DoubleContinuousSpec')): count = paramSpec.choiceCount() val_min = paramSpec.getValueFromChoice(0, count) val_max = paramSpec.getValueFromChoice(count - 1, count) step = (val_max - val_min) / (count - 1) paramRange = [val_min, step, val_max] if jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.CategoricalSpec'): count = paramSpec.choiceCount() paramRange = [] for choice in range(0, count): paramRange.append( paramSpec.getValueFromChoice(choice, count)) if jg.is_instance_of(self.gateway, paramSpec, 'bsearch.space.ConstantSpec'): paramRange = [paramSpec.getValueFromChoice(0, 1)] paramRanges.append(paramRange) return paramRanges
def testErrorInPythonCallback(self): with clientserver_example_app_process(): client_server = ClientServer( JavaParameters(), PythonParameters(propagate_java_exceptions=True)) example = client_server.entry_point.getNewExample() try: example.callHello( IHelloFailingImpl( ValueError('My interesting Python exception'))) self.fail() except Py4JJavaError as e: self.assertTrue( is_instance_of(client_server, e.java_exception, 'py4j.Py4JException')) self.assertTrue('interesting Python exception' in str(e)) try: example.callHello( IHelloFailingImpl( Py4JJavaError( '', client_server.jvm.java.lang.IllegalStateException( 'My IllegalStateException')))) self.fail() except Py4JJavaError as e: self.assertTrue( is_instance_of(client_server, e.java_exception, 'java.lang.IllegalStateException')) client_server.shutdown()
def java_to_python(obj): """Converts an arbitrary Java object to Python""" if obj is None: return None elif is_instance_of(obj, jvm.io.vertx.core.json.JsonObject) or is_instance_of(obj, jvm.io.vertx.core.json.JsonArray): return json_to_python(obj) else: return obj
def java_to_python(obj): """Converts an arbitrary Java object to Python""" if obj is None: return None elif is_instance_of(obj, jvm.io.vertx.core.json.JsonObject) or is_instance_of( obj, jvm.io.vertx.core.json.JsonArray): return json_to_python(obj) else: return obj
def __init__(self, java_object): JavaWrapper.__init__(self, java_object) if is_instance_of( gateway, java_object, gateway.jvm.boofcv.struct.distort.Point3Transform2_F32): self.is32 = True self.point_out = create_java_point_2D_f32() elif is_instance_of( gateway, java_object, gateway.jvm.boofcv.struct.distort.Point3Transform2_F64): self.is32 = False self.point_out = create_java_point_2D_f64() else: raise RuntimeError("Unexpected java object. " + java_object.getClass().getSimpleName())
def _from_java_vertex(java_vertex: JavaObject) -> 'Vertex': ctor = Vertex if is_instance_of(k._gateway, java_vertex, "io.improbable.keanu.vertices.dbl.DoubleVertex"): ctor = Double elif is_instance_of( k._gateway, java_vertex, "io.improbable.keanu.vertices.intgr.IntegerVertex"): ctor = Integer elif is_instance_of(k._gateway, java_vertex, "io.improbable.keanu.vertices.bool.BooleanVertex"): ctor = Boolean return ctor(java_vertex, None)
def visualize_lines(image, lines, title="Lines"): # If possible, convert images into a BufferedImage data type if jg.is_instance_of(gateway, image, gateway.jvm.boofcv.struct.image.ImageBase): image = gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo( image, None, True) d = gateway.jvm.java.awt.Dimension(image.getWidth(), image.getHeight()) if type(lines) is list: if len(lines) > 0 and type( lines[0]) is tuple: # See if it's a list of line and names panel = gateway.jvm.boofcv.gui.ListDisplayPanel() for o in lines: panel_lines = gateway.jvm.boofcv.gui.feature.ImageLinePanel() panel_lines.setImage(image) panel_lines.setLines( pyboof.p2b_list_LineParametric(o[1], np.float)) panel_lines.setPreferredSize(d) panel.addItem(panel_lines, o[0]) gateway.jvm.boofcv.gui.image.ShowImages.showWindow(panel, title) return else: lines = pyboof.p2b_list_LineParametric(lines, np.float) print("lines {}".format(len(lines))) print("foo {}".format(lines[0])) panel = gateway.jvm.boofcv.gui.feature.ImageLinePanel() panel.setImage(image) panel.setLines(lines) panel.setPreferredSize(d) gateway.jvm.boofcv.gui.image.ShowImages.showWindow(panel, title)
def boof_to_ndarray(boof): width = boof.getWidth() height = boof.getHeight() if jg.is_instance_of(gateway, boof, gateway.jvm.boofcv.struct.image.ImageGray): nptype = JImageDataType_to_dtype(boof.getImageType().getDataType()) boof_data = boof.getData() if pyboof.mmap_file: if nptype == np.uint8: return mmap_boof_to_numpy_U8(boof) elif nptype == np.float32: return mmap_boof_to_numpy_F32(boof) else: raise RuntimeError("Unsupported image type") else: # create copy the very slow way N = len(boof_data) print("Before painful copy {}".format(N)) data = [0] * N for i in range(N): data[i] = boof_data[i] print("After painful copy") return np.ndarray(shape=(height, width), dtype=nptype, buffer=np.array(data)) else: raise Exception("Only single band supported so far")
def set(self, o): if type(o) is LineParametric2D: self.p.set(o.p) self.slope.set(o.slope) elif jg.is_instance_of( gateway, o, gateway.jvm.georegression.struct.line.LineParametric2D_F32): self.p.set((o.getX(), o.getY())) self.slope.set((o.getSlopeX(), o.getSlopeY())) elif jg.is_instance_of( gateway, o, gateway.jvm.georegression.struct.line.LineParametric2D_F64): self.p.set((o.getX(), o.getY())) self.slope.set((o.getSlopeX(), o.getSlopeY())) else: raise Exception("Unknown object type")
def java_isinstance(java_object, java_class): ''' Convenience method to abstract away the gateway server to the Py4J `is_instance_of` method, which is documented here: https://www.py4j.org/py4j_java_gateway.html#javaobject ''' return is_instance_of(gateway, java_object, java_class)
def boof_to_ndarray( boof ): width = boof.getWidth() height = boof.getHeight() if jg.is_instance_of(gateway, boof, gateway.jvm.boofcv.struct.image.ImageGray): nptype = JImageDataType_to_dtype(boof.getImageType().getDataType()) boof_data = boof.getData() if pyboof.mmap_file: if nptype == np.uint8: return mmap_boof_to_numpy_U8(boof) elif nptype == np.float32: return mmap_boof_to_numpy_F32(boof) else: raise RuntimeError("Unsupported image type") else: # create copy the very slow way N = len(boof_data) print "Before painful copy {}".format(N) data = [0]*N for i in xrange(N): data[i] = boof_data[i] print "After painful copy" return np.ndarray(shape=(height,width), dtype=nptype, buffer=np.array(data)) else: raise Exception("Only single band supported so far")
def call(self, milliseconds, jrdds): # Clear the failure self.failure = None try: if self.ctx is None: self.ctx = SparkContext._active_spark_context if not self.ctx or not self.ctx._jsc: # stopped return # extend deserializers with the first one sers = self.deserializers if len(sers) < len(jrdds): sers += (sers[0], ) * (len(jrdds) - len(sers)) rdds = [ self.rdd_wrap_func(jrdd, self.ctx, ser) if jrdd else None for jrdd, ser in zip(jrdds, sers) ] t = datetime.fromtimestamp(milliseconds / 1000.0) r = self.func(t, *rdds) if r: # Here, we work around to ensure `_jrdd` is `JavaRDD` by wrapping it by `map`. # org.apache.spark.streaming.api.python.PythonTransformFunction requires to return # `JavaRDD`; however, this could be `JavaPairRDD` by some APIs, for example, `zip`. # See SPARK-17756. if is_instance_of(self.ctx._gateway, r._jrdd, "org.apache.spark.api.java.JavaRDD"): return r._jrdd else: return r.map(lambda x: x)._jrdd except: self.failure = traceback.format_exc()
def __get_ndarray_from_tensor(java_tensor) -> ndarray: # Performance is much better using byte arrays where possible. # https://stackoverflow.com/questions/39095994/fast-conversion-of-java-array-to-numpy-array-py4j if is_instance_of(k._gateway, java_tensor, "io.improbable.keanu.tensor.dbl.DoubleTensor"): byteArray = k.jvm_view().Py4jByteArrayConverter.toByteArray(java_tensor.asFlatDoubleArray()) doubleArray = np.frombuffer(byteArray, np.float64) return doubleArray elif is_instance_of(k._gateway, java_tensor, "io.improbable.keanu.tensor.intgr.IntegerTensor"): byteArray = k.jvm_view().Py4jByteArrayConverter.toByteArray(java_tensor.asFlatIntegerArray()) intArray = np.frombuffer(byteArray, np.int32) return intArray elif is_instance_of(k._gateway, java_tensor, "io.improbable.keanu.tensor.bool.BooleanTensor"): byteArray = k.jvm_view().Py4jByteArrayConverter.toByteArray(java_tensor.asFlatBooleanArray()) boolArray = np.frombuffer(byteArray, bool) return boolArray else: return np.array(list(java_tensor.asFlatArray()))
def convert_reference_type(target_id, gateway_client: GatewayClient, java_gateway: JavaGateway): java_object = JavaObject(target_id, gateway_client) if is_instance_of(java_gateway, java_object, "java.time.LocalDate"): return date(java_object.getYear(), java_object.getMonthValue(), java_object.getDayOfMonth()) else: return java_object
def java_round_trip(type, value, check_binding=True): j_value = type.to_java(value) if value is not None and check_binding: assert is_instance_of(java_gateway, j_value, type.binding) py_value = type.from_java(j_value) assert value == py_value
def _convert_delta_exception(e: "JavaObject") -> Optional[CapturedException]: """ Convert Delta's Scala concurrent exceptions to the corresponding Python exceptions. """ s: str = e.toString() c: "JavaObject" = e.getCause() jvm: "JVMView" = SparkContext._jvm # type: ignore[attr-defined] gw = SparkContext._gateway # type: ignore[attr-defined] stacktrace = jvm.org.apache.spark.util.Utils.exceptionString(e) # Temporary workaround until Delta Lake is upgraded to Spark 3.3 # Below three exception handling cases are copied from # https://github.com/apache/spark/blob/master/python/pyspark/sql/utils.py#L156 if is_instance_of(gw, e, "org.apache.spark.sql.catalyst.parser.ParseException"): return ParseException(s.split(': ', 1)[1], stacktrace, c) # Order matters. ParseException inherits AnalysisException. if is_instance_of(gw, e, "org.apache.spark.sql.AnalysisException"): return AnalysisException(s.split(': ', 1)[1], stacktrace, c) if is_instance_of(gw, e, "java.lang.IllegalArgumentException"): return IllegalArgumentException(s.split(': ', 1)[1], stacktrace, c) if s.startswith( 'io.delta.exceptions.DeltaConcurrentModificationException: '): return DeltaConcurrentModificationException( s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.ConcurrentWriteException: '): return ConcurrentWriteException(s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.MetadataChangedException: '): return MetadataChangedException(s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.ProtocolChangedException: '): return ProtocolChangedException(s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.ConcurrentAppendException: '): return ConcurrentAppendException(s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.ConcurrentDeleteReadException: '): return ConcurrentDeleteReadException( s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.ConcurrentDeleteDeleteException: '): return ConcurrentDeleteDeleteException( s.split(': ', 1)[1], stacktrace, c) if s.startswith('io.delta.exceptions.ConcurrentTransactionException: '): return ConcurrentTransactionException( s.split(': ', 1)[1], stacktrace, c) return None
def getSqlState(self) -> Optional[str]: assert SparkContext._gateway is not None gw = SparkContext._gateway if self._origin is not None and is_instance_of( gw, self._origin, "org.apache.spark.SparkThrowable"): return self._origin.getSqlState() else: return None
def getErrorClass(self) -> Optional[str]: assert SparkContext._gateway is not None # type: ignore[attr-defined] gw = SparkContext._gateway # type: ignore[attr-defined] if self._origin is not None and is_instance_of( gw, self._origin, "org.apache.spark.SparkThrowable"): return self._origin.getErrorClass() else: return None
def getErrorClass(self): assert SparkContext._gateway is not None gw = SparkContext._gateway if self._origin is not None and is_instance_of( gw, self._origin, "org.apache.spark.SparkThrowable"): return self._origin.getErrorClass() else: return None
def boof_to_ndarray( boof ): width = boof.getWidth() height = boof.getHeight() if jg.is_instance_of(gateway, boof, gateway.jvm.boofcv.struct.image.ImageSingleBand ): data = boof.getData() nptype = JImageDataType_to_dtype(boof) return np.ndarray(shape=(height,width), dtype=nptype, buffer=data) else: raise Exception("Only single band supported so far")
def set(self, o): if type(o) is Point2D: self.x = o.x self.y = o.y elif type(o) is tuple: self.x = o[0] self.y = o[1] elif jg.is_instance_of( gateway, o, gateway.jvm.georegression.struct.point.Point2D_F64): self.x = o.getX() self.y = o.getY() elif jg.is_instance_of( gateway, o, gateway.jvm.georegression.struct.point.Point2D_F32): self.x = o.getX() self.y = o.getY() else: raise Exception("Unknown object type")
def boof_to_ndarray(boof): width = boof.getWidth() height = boof.getHeight() if jg.is_instance_of(gateway, boof, gateway.jvm.boofcv.struct.image.ImageSingleBand): data = boof.getData() nptype = JImageDataType_to_dtype(boof) return np.ndarray(shape=(height, width), dtype=nptype, buffer=data) else: raise Exception("Only single band supported so far")
def testBinarySuccess(self): e = self.gateway.getNewExample() # not binary - just get the Java object v1 = e.getStream() self.assertTrue(is_instance_of(self.gateway, v1, "java.nio.channels.ReadableByteChannel")) # pull it as a binary stream with e.getStream.stream() as conn: self.assertTrue(isinstance(conn, GatewayConnectionGuard)) expected = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." self.assertEqual(expected, smart_decode(conn.read(len(expected))))
def set(self, src): if isinstance(src, Polygon2D): self.vertexes = [] for v in src.vertexes: self.vertexes.append(v.copy()) elif jg.is_instance_of( gateway, src, gateway.jvm.georegression.struct.shapes.Polygon2D_F64): self.vertexes = [] for i in range(src.size()): self.vertexes.append(Point2D(src.get(i))) elif jg.is_instance_of( gateway, src, gateway.jvm.georegression.struct.shapes.Polygon2D_F32): self.vertexes = [] for i in range(src.size()): self.vertexes.append(Point2D(src.get(i))) else: self.vertexes = [] for v in src: self.vertexes.append(Point2D(v[0], v[1]))
def set(self, o): if type(o) is Point2D: self.x = o.x self.y = o.y if type(o) is tuple: self.x = o[0] self.y = o[1] elif jg.is_instance_of(gateway, o, gateway.jvm.georegression.struct.point.Point2D_F64 ): self.x = o.getX() self.y = o.getY() else: raise Exception("Unknown object type")
def visualize_matches(image_left , image_right , points_src , points_dst , match_indexes, title = "Associated Features"): if type(points_src) is list: points_src = pyboof.p2b_list_point2DF64(points_src) if type(points_dst) is list: points_dst = pyboof.p2b_list_point2DF64(points_dst) if type(match_indexes) is list: raise Exception("Haven't bothered to implement python to java conversion for match_indexes yet") # If possible, convert images into a BufferedImage data type if jg.is_instance_of(gateway, image_left, gateway.jvm.boofcv.struct.image.ImageBase): image_left = gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo(image_left, None, True) if jg.is_instance_of(gateway, image_right, gateway.jvm.boofcv.struct.image.ImageBase): image_right = gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo(image_right, None, True) panel = gateway.jvm.boofcv.gui.feature.AssociationPanel(20) panel.setImages( image_left, image_right) panel.setAssociation(points_src, points_dst, match_indexes) gateway.jvm.boofcv.gui.image.ShowImages.showWindow(panel, title)
def set(self, o): if type(o) is Quadrilateral2D: self.a.set(o.a) self.b.set(o.b) self.c.set(o.c) self.d.set(o.d) elif jg.is_instance_of(gateway, o, gateway.jvm.georegression.struct.shapes.Quadrilateral_F64 ): self.a.set(o.getA()) self.b.set(o.getB()) self.c.set(o.getC()) self.d.set(o.getD()) else: raise Exception("Unknown object type")
def testBinarySuccess(self): e = self.gateway.getNewExample() # not binary - just get the Java object v1 = e.getStream() self.assertTrue( is_instance_of(self.gateway, v1, "java.nio.channels.ReadableByteChannel")) # pull it as a binary stream with e.getStream.stream() as conn: self.assertTrue(isinstance(conn, GatewayConnectionGuard)) expected =\ u"Lorem ipsum dolor sit amet, consectetur adipiscing elit." self.assertEqual(expected, smart_decode(conn.read(len(expected))))
def show_grid( images , columns=-1, title="Image Grid"): if type(images) is not tuple or not list: images = (images) array = gateway.new_array(gateway.jvm.java.awt.image.BufferedImage,len(images)) for idx,image in enumerate(images): if jg.is_instance_of(gateway, image, gateway.jvm.java.awt.image.BufferedImage ): array[idx] = image else: array[idx] = gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo(image,None,True) # If no grid is specified try to make it square if columns <= 0: columns = int(math.sqrt(len(images))) gateway.jvm.boofcv.gui.image.ShowImages.showGrid(columns, title, array)
def testProxyError(self): sleep() example = self.gateway.entry_point.getNewExample() try: example.callHello(IHelloFailingImpl( Py4JJavaError( '', self.gateway.jvm.java.lang.IllegalStateException( 'My IllegalStateException')))) self.fail() except Py4JJavaError as e: self.assertTrue(is_instance_of( self.gateway, e.java_exception, 'py4j.Py4JException')) self.assertIn('My IllegalStateException', str(e))
def set(self, o): if type(o) is Quadrilateral2D: self.a.set(o.a) self.b.set(o.b) self.c.set(o.c) self.d.set(o.d) elif jg.is_instance_of( gateway, o, gateway.jvm.georegression.struct.shapes.Quadrilateral_F64): self.a.set(o.getA()) self.b.set(o.getB()) self.c.set(o.getC()) self.d.set(o.getD()) else: raise Exception("Unknown object type")
def show_list(image_name_pairs, title="Image List"): if type(image_name_pairs) is not tuple or not list: image_name_pairs = (image_name_pairs) names = [] buffered = [] for pair in image_name_pairs: if jg.is_instance_of(gateway, pair[0], gateway.jvm.java.awt.image.BufferedImage ): buffered.append(pair[0]) else: buffered.append( gateway.jvm.boofcv.io.image.ConvertBufferedImage.convertTo(pair[0],None,True) ) names.append(pair[1]) panel = gateway.jvm.boofcv.gui.ListDisplayPanel() for i in range(len(names)): panel.addImage(buffered[i],names[i]) gateway.jvm.boofcv.gui.image.ShowImages.showWindow(panel, title)
def testIsInstance(self): a_list = self.gateway.jvm.java.util.ArrayList() a_map = self.gateway.jvm.java.util.HashMap() # FQN self.assertTrue(is_instance_of(self.gateway, a_list, "java.util.List")) self.assertFalse(is_instance_of(self.gateway, a_list, "java.lang.String")) # JavaClass self.assertTrue(is_instance_of(self.gateway, a_list, self.gateway.jvm.java.util.List)) self.assertFalse(is_instance_of(self.gateway, a_list, self.gateway.jvm.java.lang.String)) # JavaObject self.assertTrue(is_instance_of(self.gateway, a_list, a_list)) self.assertFalse(is_instance_of(self.gateway, a_list, a_map))
def testStream(self): with clientserver_example_app_process(): client_server = ClientServer( JavaParameters(), PythonParameters()) e = client_server.entry_point.getNewExample() # not binary - just get the Java object v1 = e.getStream() self.assertTrue( is_instance_of( client_server, v1, "java.nio.channels.ReadableByteChannel")) # pull it as a binary stream with e.getStream.stream() as conn: self.assertTrue(isinstance(conn, GatewayConnectionGuard)) expected =\ u"Lorem ipsum dolor sit amet, consectetur adipiscing elit." self.assertEqual( expected, smart_decode(conn.read(len(expected)))) client_server.shutdown()
def is_jvm_instance_of(self, item, scala_type): if self.is_java(item): return _py4j_gateway.is_instance_of(self.sc._gateway, item, scala_type) return False