STEP file reading issue in Python - python-3.x

I am using Python3.4.2 and pythonOCC-0.16.0-win32-py34.exe to draw components. Every components are rendered properly with one defined color but that is not look like a real world component.
Above image is my Python implementation which generate 3D image from STEP file with one color.
Below image is rendered one of my windows software and there I have used Step file. I want to render component same as look like in below image so its look like a real world component.
Is there any way to get correct colored output in Python by read STEP file? I have searched a lot but didn't get a way to implement it. Please help me to go in forward direction.
from future import print_function
import sys
#from OCC.STEPCAFControl import STEPCAFControl_Reader
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Display.SimpleGui import init_display
from OCC.Display.WebGl import threejs_renderer
step_reader = STEPControl_Reader()
status = step_reader.ReadFile('./models/test.STEP')
if status == IFSelect_RetDone: # check status
failsonly = False
step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
ok = step_reader.TransferRoot(1)
_nbs = step_reader.NbShapes()
aResShape = step_reader.Shape(1)
else:
print("Error: can't read file.")
sys.exit(0)
#display, start_display, add_menu, add_function_to_menu = init_display()
#display.DisplayShape(aResShape, update=True)
#start_display()
my_renderer = threejs_renderer.ThreejsRenderer(background_color="#123345")
my_renderer.DisplayShape(aResShape)
The above code is used for read STEP file using Python.

Related

Is it possible to use Google's ortool in my script without downloaded ortool library?

Basically, I have to test my script on a server which I cant add new libraries. How do i write/change my
from ortools.algorithms import pywrapknapsack_solver
in my .py file such that I can still utilise Google's ortool when i submit onto a server without ortools installed? Is there something like html tag which i can just link to and use ortool library?
I have to sent my whole code.py file to test, and i can add along other .py files with my code.py.
I tried to download from Google the source code but i dont know how to get it to work.
Currently my code.py:
from __future__ import print_function
from ortools.algorithms import pywrapknapsack_solver
def getBestSet(W, packages):
final_arr = []
pID = ['1','2','3','4','5'] #sample data
values = [20,44,12,5,16]
weights = [10,11,21,3,9]
solver = pywrapknapsack_solver.KnapsackSolver(
pywrapknapsack_solver.KnapsackSolver.
KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')
solver.Init(values, [weights], [W])
computed_value = solver.Solve()
packed_items = []
packed_weights = []
total_weight = 0
# print('Total value =', computed_value)
for i in range(len(values)):
if solver.BestSolutionContains(i):
packed_items.append(i)
packed_weights.append(weights[i])
total_weight += weights[i]
# print('Total weight:', total_weight)
# print('Packed items:', packed_items)
# print('Packed_weights:', packed_weights)
for i in packed_items:
final_arr.append(pID[i])
return final_arr
You can try on Google Colab.
To install or-tools, in the first cell, run !pip install ortools
then put your code in a new cell below the first one.

Rendering a gltf/glb file in jupyter notebook using vtk and k3d

I have explored the available methods of how to render a gltf/glb file inline in a jupyter notebook to keep the viewer callback interactivity intact. I have eventually ended up using vtk and k3d to achieve this. The two hurdles I have are:
How to use the vtkGLTFReader() to get vtkPolyData objects from the
glb and render these in k3d? SOLUTION: See method posted in the comments.
How to display colors/textures embedded in the gltf/glb to show them in
k3d?
Here is the code to get vtkPolyData and pass it to k3d.
import k3d
import vtk
import ipywidgets as widgets
reader = vtk.vtkGLTFReader()
reader.SetFileName('sample_glb/GroundVehicle.glb')
reader.Update()
plot = k3d.plot()
mb = reader.GetOutput()
iterator = mb.NewIterator()
vtk_polyobjects = []
while not iterator.IsDoneWithTraversal():
item = iterator.GetCurrentDataObject()
vtk_polyobjects.append(item)
iterator.GoToNextItem()
for obj in vtk_polyobjects:
plot += k3d.vtk_poly_data(obj, color=0x222222)
plot.display()
debug_info = widgets.HTML()

Understanding argparse to get dynamic maps with Geo-Location of tweets

I have found this python code online (twitter_map_clustered.py) which (I think) help create a map using the geodata of different tweets.:
from argparse import ArgumentParser
import folium
from folium.plugins import MarkerCluster
import json
def get_parser():
parser = ArgumentParser()
parser.add_argument('--geojson')
parser.add_argument('--map')
return parser
def make_map(geojson_file, map_file):
tweet_map = folium.Map(Location=[50, 5], max_zoom=20)
marker_cluster = MarkerCluster().add_to(tweet_map)
geodata= json.load(open(geojson_file))
for tweet in geodata['features']:
tweet['geometry']['coordinates'].reverse()
marker = folium.Marker(tweet['geometry']['coordinates'], popup=tweet['properties']['text'])
marker.add_to(marker_cluster)
#Save to HTML map file
tweet_map.save(map_file)
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
make_map(args.geojson, args.map)
I managed to extract the geo information of different tweets and save it into a geo_data.json file. However, I have trouble understanding the code, specially the function def get_parser().
It seems that we need to add argument when running the file in the command prompt. The argument should be geo_data.json. However, it is also asking for a map ? parser.add_argument('--map')
Why is it the case? In the code, aren't we creating the map here?
#Save to HTML map file
tweet_map.save(map_file)
Can you please help me. How would you run the python script ? Is there anything important I am missing ?
As explained by argparse documentation, it simply asks for the name of the geojson file and a name that your code will use to save the map.
Therefore, you will run:
python twitter_map_clustered.py --geojson geo_data.json --map mymap.html
and you will get a map named mymap.html.

Python Pillow ImageChops.difference always None

I'm trying to compare screenshots of 2 interactive maps. The screenshots are taken with Selenium and using Pillow to compare.
...
from selenium.webdriver.common.by import By
from selenium import webdriver
from io import BytesIO
from PIL import ImageChops, Image
...
png_bytes1 = driver.find_element(By.CSS_SELECTOR, "body").screenshot_as_png
png_bytes2 = driver2.find_element(By.CSS_SELECTOR, "body").screenshot_as_png
img1 = Image.open(BytesIO(png_bytes1))
img2 = Image.open(BytesIO(png_bytes2))
diff = ImageChops.difference(img1, img2)
print(diff.getbbox())
But diff is always blank. I manually used img1.show() and img2.show() to obtain the images below. diff.show() is always blank and diff.getbbox() prints None. What am I doing wrong and is there a better way of doing it?
Update: It works if I first save these images as jpg. Anyone have ideas why?
It seems ImageChops.difference() will only work if the image parameters are Image objects. PNG files are PngImageFile objects, with an RGBA mode for an extra alpha layer and need to be converted using converted_img1 = img1.convert('RGB').

'spaceship' class is not defined (even though I've imported it?)

I run the main module, which should work correctly. But an error gets returned. 'spaceship' is not defined when I define 's=spaceship(parameters)' why is this I don't get it. I'm using zelle graphics for python. thank you
Functions from main module:
spaceshipGame file
from graphics import *
from spaceshipClass import *
def main():
window=createGraphicsWindow()
runGame(window)
def createGraphicsWindow():
win=GraphWin("Spaceship game",800,800)
return win
def createSpaceship(window,p1,p2,p3,speed,colour):
s=spaceship(window,p1,p2,p3,speed,colour)
return s
def runGame(window):
player=createSpaceship(window,Point(500,500),Point(500,470),Point(520,485),0.5,"red")
player.draw(window)
main()
spaceshipClass file
from spaceshipGame import *
from graphics import *
class spaceship:
def __init__(self,window,p1,p2,p3,speed,colour):
self.p1=p1
self.p2=p2
self.p3=p3
self.speed=speed
self.colour=colour
self.window=window
Never mind, I see the problem. Consult this example for more information:
Simple cross import in python
But the problem is the way you are cross importing, so delete from spaceshipGame import * from spaceshipClass or vise-versa (i.e. delete from spaceshipClass import * from spaceshipGame). You can import individually if you need to like in the example I provided.
There are also many other ways around it if you read the example. One of the easiest would be just merging them in the same file if they need to share a lot of methods.

Resources