kleine Mathe-Spielereien

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

11.5. 2024Hier eisn erdstes Beispiel
Zusamen mit vielen anderen Bibliotheken
eröffnen sich mit graphviz für mich jetzt
viele neue Aspekte.
Gruß OSWALD

Code: Alles auswählen


import graphviz

f = graphviz.Digraph('finite_state_machine', filename='fsm.gv')
f.attr(rankdir='LR', size='8,5')

f.attr('node', shape='doublecircle')
f.node('LR_0')
f.node('LR_3')
f.node('LR_4')
f.node('LR_8')

f.attr('node', shape='circle')
f.edge('LR_0', 'LR_2', label='SS(B)')
f.edge('LR_0', 'LR_1', label='SS(S)')
f.edge('LR_1', 'LR_3', label='S($end)')
f.edge('LR_2', 'LR_6', label='SS(b)')
f.edge('LR_2', 'LR_5', label='SS(a)')
f.edge('LR_2', 'LR_4', label='S(A)')
f.edge('LR_5', 'LR_7', label='S(b)')
f.edge('LR_5', 'LR_5', label='S(a)')
f.edge('LR_6', 'LR_6', label='S(b)')
f.edge('LR_6', 'LR_5', label='S(a)')
f.edge('LR_7', 'LR_8', label='S(b)')
f.edge('LR_7', 'LR_5', label='S(a)')
f.edge('LR_8', 'LR_6', label='S(b)')
f.edge('LR_8', 'LR_5', label='S(a)')

f.view()
print(f) 







OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

11.5.2024
Ein schönes Beispiel für die Leistungsgähigkeit von Python
zusammen mit graphviz.
Gruss OSWALD

Code: Alles auswählen

import graphviz

t = graphviz.Digraph('TrafficLights', filename='traffic_lights.gv',
                     engine='neato')

t.attr('node', shape='box')
for i in (2, 1):
    t.node(f'gy{i:d}')
    t.node(f'yr{i:d}')
    t.node(f'rg{i:d}')

t.attr('node', shape='circle', fixedsize='true', width='0.9')
for i in (2, 1):
    t.node(f'green{i:d}')
    t.node(f'yellow{i:d}')
    t.node(f'red{i:d}')
    t.node(f'safe{i:d}')

for i, j in [(2, 1), (1, 2)]:
    t.edge(f'gy{i:d}', f'yellow{i:d}')
    t.edge(f'rg{i:d}', f'green{i:d}')
    t.edge(f'yr{i:d}', f'safe{j:d}')
    t.edge(f'yr{i:d}', f'red{i:d}')
    t.edge(f'safe{i:d}', f'rg{i:d}')
    t.edge(f'green{i:d}', f'gy{i:d}')
    t.edge(f'yellow{i:d}', f'yr{i:d}')
    t.edge(f'red{i:d}', f'rg{i:d}')

t.attr(overlap='false')
t.attr(label=r'PetriNet Model TrafficLights\n'
             r'Extracted from ConceptBase and layed out by Graphviz')
t.attr(fontsize='4')

t.view()



OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

12.5.2024
scikit-image ist eine Sammlung von Algorithmen zur Bildverarbeitung.
'Unscheinbar' kommt es als 'skimage ' daher ,aber seine Bedeutung in der
Bildbearbeitung und damit in der KI ist kaum zu überschätzen.
Jedoch ist es auch in diesem Fall nicht ganz einfach es zu implementieren.
Mit Windows -Powershell wird es so imnstalliert:

pip install scikit-image.
Dann aber eröffnet sich ein weites Feld von Anwendungen.
Hier wieder ein erstes Beispiel. weitere folgen wieder.
Gruss OSWALD

Code: Alles auswählen



# Darstellung von square(15), rectangle(15, 10), diamond(7), disk(7), octagon(7, 4), star(5), cube(11), octahedron(5), ball(5)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from skimage.morphology import (
    square,
    rectangle,
    diamond,
    disk,
    cube,
    octahedron,
    ball,
    octagon,
    star,
)

# Generate 2D and 3D structuring elements.
struc_2d = {
    "square(15)": square(15),
    "rectangle(15, 10)": rectangle(15, 10),
    "diamond(7)": diamond(7),
    "disk(7)": disk(7),
    "octagon(7, 4)": octagon(7, 4),
    "star(5)": star(5),
}

struc_3d = {"cube(11)": cube(11), "octahedron(5)": octahedron(5), "ball(5)": ball(5)}

# Visualize the elements.
fig = plt.figure(figsize=(8, 8))

idx = 1
for title, struc in struc_2d.items():
    ax = fig.add_subplot(3, 3, idx)
    ax.imshow(struc, cmap="Paired", vmin=0, vmax=12)
    for i in range(struc.shape[0]):
        for j in range(struc.shape[1]):
            ax.text(j, i, struc[i, j], ha="center", va="center", color="w")
    ax.set_axis_off()
    ax.set_title(title)
    idx += 1

for title, struc in struc_3d.items():
    ax = fig.add_subplot(3, 3, idx, projection=Axes3D.name)
    ax.voxels(struc)
    ax.set_title(title)
    idx += 1

fig.tight_layout()
plt.show()


OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

13.5.2024
Hier ein kompliziertes Beispiel, noch mit einem kleinen Fehler behaftet,
der noch zu suchen wäre.
Es tauchen immer neue Begriffe auf , die ich zu klären versuche.
Mit Demut und Staunen versuche ich mich
Python und seinen Bibliotheken zu nähern ujnd ich weiss, dass ich den
OLYMP nie bezwingen kann, aber noch treibt mich die Neugier.
Gute Zeit OSWALD

Code: Alles auswählen

mport matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pooch                        #'Hündchen, das die Dateien herbeiholt.
#                                          Windows- Powershell:     pip install pooch  
from skimage import data

matplotlib.rcParams['font.size'] = 18

images = (
    'astronaut',
    'binary_blobs',
    'brick',
    'colorwheel',
    'camera',
    'cat',
    'checkerboard',
    'clock',
    'coffee',
    'coins',
    'eagle',
    'grass',
    'gravel',
    'horse',
    'logo',
    'page',
    'text',
    'rocket',
)


for name in images:
    caller = getattr(data, name)
    image = caller()
    plt.figure()
    plt.title(name)
    if image.ndim == 2:
        plt.imshow(image, cmap=plt.cm.gray)
    else:
        plt.imshow(image)



#text rocket
#Thumbnail image for the gallery

fig, axs = plt.subplots(nrows=3, ncols=3)
for ax in axs.flat:
    ax.axis("off")
axs[0, 0].imshow(data.astronaut())
axs[0, 1].imshow(data.binary_blobs(), cmap=plt.cm.gray)
axs[0, 2].imshow(data.brick(), cmap=plt.cm.gray)
axs[1, 0].imshow(data.colorwheel())
axs[1, 1].imshow(data.camera(), cmap=plt.cm.gray)
axs[1, 2].imshow(data.cat())
axs[2, 0].imshow(data.checkerboard(), cmap=plt.cm.gray)
axs[2, 1].imshow(data.clock(), cmap=plt.cm.gray)
further_img = np.full((300, 300), 255)
for xpos in [100, 150, 200]:
    further_img[150 - 10 : 150 + 10, xpos - 10 : xpos + 10] = 0
axs[2, 2].imshow(further_img, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=0.1, hspace=0.1)

plt.show()


OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

3.5.2024
In diesem Beispiel wird neben viel Mathematik
auch ein Signal/Abtastfehler demonstriert.
Das Thema ' Bild -Verarbeitung ' enthält quasi
Gesamt-Python mit all seinen seinen Bibliotheken und
gehört selbstverständlich auch zur KI.
Gute Zeit OSWALD

Code: Alles auswählen


                        Was versteht man unter Aliasing-Effekt?
#   Der Aliasing-Effekt ist ein Fehler im erfassten Messsignal,
#   welcher durch eine falsch gesetzte Abtastrate auftritt.
#   Durch eine zu tiefe Abtastrate wird das Nyquist-Shannon Abtasttheorem nicht beachtet und
#   somit das Messsignal nicht korrekt erfasst.


import math
import numpy as np
import matplotlib.pyplot as plt

from skimage.draw import (
    line,
    polygon,
    disk,
    circle_perimeter,
    ellipse,
    ellipse_perimeter,
    bezier_curve,
)


fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(10, 6))


img = np.zeros((500, 500, 3), dtype=np.double)

# draw line
rr, cc = line(120, 123, 20, 400)
img[rr, cc, 0] = 255

# fill polygon
poly = np.array(
    (
        (300, 300),
        (480, 320),
        (380, 430),
        (220, 590),
        (300, 300),
    )
)
rr, cc = polygon(poly[:, 0], poly[:, 1], img.shape)
img[rr, cc, 1] = 1

# fill circle
rr, cc = disk((200, 200), 100, shape=img.shape)
img[rr, cc, :] = (1, 1, 0)

# fill ellipse
rr, cc = ellipse(300, 300, 100, 200, img.shape)
img[rr, cc, 2] = 1

# circle
rr, cc = circle_perimeter(120, 400, 15)
img[rr, cc, :] = (1, 0, 0)

# Bezier curve
rr, cc = bezier_curve(70, 100, 10, 10, 150, 100, 1)
img[rr, cc, :] = (1, 3  ,0)

# ellipses
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 4.0)
img[rr, cc, :] = (1, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.0)
img[rr, cc, :] = (0, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 5.0)
img[rr, cc, :] = (1, 3, 1)

ax1.imshow(img)
ax1.set_title('Kein Abtastfehler',)
ax1.axis('off')


from skimage.draw import line_aa, circle_perimeter_aa


img = np.zeros((100, 100), dtype=np.double)

# anti-aliased line             # also
rr, cc, val = line_aa(12, 12, 20, 50)
img[rr, cc] = val

# anti-aliased circle
rr, cc, val = circle_perimeter_aa(60, 40, 30)
img[rr, cc] = val


ax2.imshow(img, cmap=plt.cm.Blues)
ax2.set_title('Abtastfehler')
ax2.axis('off')

plt.show()


OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

15.5.2024
Zuletzt zeiege ie man sich über Zufallszahlen
sich beliebige Figuren basteln kann.
dann versuche ich , mich ein wenig der Bibliothek OPENECV(cv2) zu nähern.
Das kann dauern.
Gruss OSWALD

Code: Alles auswählen



#                          original                  Image shape: (128, 128)
#                          original                  Labels: [('rectangle', ((64, 82), (80, 96)))]

import matplotlib.pyplot as plt

from skimage.draw import random_shapes

# Let's start simple and generate a 128x128 image
# with a single grayscale rectangle.
result = random_shapes(
    (255, 255), max_shapes=1, shape='rectangle', channel_axis=None, rng=0)

# We get back a tuple consisting of (1) the image with the generated shapes
# and (2) a list of label tuples with the kind of shape (e.g. circle,
# rectangle) and ((r0, r1), (c0, c1)) coordinates.
image, labels = result
print(f'Image shape: {image.shape}\nLabels: {labels}')

# We can visualize the images.
fig, axes = plt.subplots(nrows=2, ncols=3)
ax = axes.ravel()
ax[0].imshow(image, cmap='gray')
ax[0].set_title('Grayscale shape')

# The generated images can be much more complex. For example, let's try many
# shapes of any color. If we want the colors to be particularly light, we can
# set the `intensity_range` to an upper subrange of (0,255).
image1, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((10, 255),))

# Moar :)
image2, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((20, 55),))
image3, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((25, 155),))
image4, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((55, 145),))

for i, image in enumerate([image1, image2, image3, image4], 1):
    ax[i].imshow(image)
    ax[i].set_title(f'Colored shapes, #{i-1}')

# These shapes are well suited to test segmentation algorithms. Often, we
# want shapes to overlap to test the algorithm. This is also possible:
image, _ = random_shapes(
    (128, 128), min_shapes=5, max_shapes=16, min_size=10, allow_overlap=True
)
ax[5].imshow(image)
ax[5].set_title('Overlapping shapes')

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.show()


OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

15,5,2024
(Zum Schluß noch ein 3dimensionales Bild.
(wer immer strebend sich bemüht, den können wir erlösem Goethe FaustII)
Gute Zeit Oswald

Code: Alles auswählen


  3d CUBES


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

from skimage import measure
from skimage.draw import ellipsoid


# Generate a level set about zero of two identical ellipsoids in 3D
ellip_base = ellipsoid(6, 10, 16, levelset=True)
ellip_double = np.concatenate((ellip_base[:-1, ...], ellip_base[2:, ...]), axis=0)

# Use marching cubes to obtain the surface mesh of these ellipsoids
verts, faces, normals, values = measure.marching_cubes(ellip_double, 0)

# Display resulting triangular mesh using Matplotlib. This can also be done
# with mayavi (see skimage.measure.marching_cubes docstring).
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')

# Fancy indexing: `verts[faces]` to generate a collection of triangles
mesh = Poly3DCollection(verts[faces])
mesh.set_edgecolor('k')
ax.add_collection3d(mesh)

ax.set_xlabel("x-axis: a = 6 per ellipsoid")
ax.set_ylabel("y-axis: b = 10")
ax.set_zlabel("z-axis: c = 16")

ax.set_xlim(0, 24)  # a = 6 (times two for 2nd ellipsoid)
ax.set_ylim(0, 20)  # b = 10
ax.set_zlim(0, 32)  # c = 16

plt.tight_layout()
plt.show()


OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

18.5,2024
Mein Einstieg in VCV2
Farben und Bilder. Die Probleme mit den Farben
versuche ich zuerst zu klären.Im folgenden Code
stelle ich die Konvertierung zu zwei Farbräumen vor.
In Ermanglung von Bildern aktiviere ich
meine Webcam und untersUche mein Selfie.
Sie werden also mein Konterfei nicht sehen !

Das alles zu einer ersten orientierung,
damit ich weiß wo es lang gehen soll.
Dann geht es um die Bilder.
Gute Zeit OSWALD

Code: Alles auswählen

#      Konvertierung  in  einen   anderen Farbraum 
import cv2

         # initialisiere WebCam
cam = cv2.VideoCapture(0)
 
# man  positioniere sich vor der  WebCam  und  dann F5
ret, image = cam.read()
print(image)
print(ret)
# konvertiere sein Abbild einmal in den Farbraum GRAY und dann  in HSV
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

## zeige das Bild an
cv2.imshow("Bild wurde modifiziert", image)
 
# warte auf Tastendruck (wichtig, sonst sieht man das Fenster nicht)
cv2.waitKey(0)

OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

19.5.2024
Für den Fall, dass die Kamera überprüft werden soll,
weil kein Bild bzw. weil kein Video zu sehen ist,
kann man das hiermit überprüfen.
Den Code habe ich zufällig entdeckt.
Gute Zeit OSWALD

Code: Alles auswählen

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # The  operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('Hit ESC to close', gray)
    if cv.waitKey(1) & 0xFF == 27:
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()


OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

20.5.2024
Leider komme ch derzeit bei Opencv nicht weiter.
Sxchukd ist der folgende Fehler:

" TypeError: Image data of dtype object cannot be converted to float"
Im Netz finden sich sehr zahlreiche Erklärungen,
angefangen von 'Windows für wissemschaftliches Rechnen nicht geeignet
bis " China blockiert etwas " , aber keine wirkliche Lösung des Problems.
Ich versiuche es aber weiter.
Guten Zeit OSWALD
OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

20...5.2024
Oder liegt es am fakschen Pfad , weil dann das 'ild' leer ist ?
OSWALD
OSWALD
User
Beiträge: 376
Registriert: Freitag 18. März 2022, 17:32

21.5.2024
Inzwischen weiß ich, dass auch für OPENCV
GPU und entsprechende Graphikarten notwendig sind.
Daher bleibe ich bei Dkimage und zeige
ein Beispiel , in dem Farbkanäle mit hue ,. threshhold und value-Werten
demonstriert werden.
Man kann diese Werte auch variieren.
Gute Zeit OSWALD

Code: Alles auswählen


import matplotlib.pyplot as plt
import skimage

from skimage import data
from skimage.color import rgb2hsv     #         
#Wir laden zunächst das RGB-Bild         und               extrahieren die Hue- und Value-Kanäle:

rgb_img = data.coffee()
hsv_img = rgb2hsv(rgb_img)              #    alternativ  hsv
hue_img = hsv_img[:, :, 0]
value_img = hsv_img[:, :, 2]

fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(5, 4))

ax0.imshow(rgb_img)
ax0.set_title("RGB image")
ax0.axis('off')
ax1.imshow(hue_img, cmap='hsv')
ax1.set_title("Hue channel")
ax1.axis('off')
ax2.imshow(value_img)
ax2.set_title("Value channel")
ax2.axis('off')

fig.tight_layout()


#      RGB-Bild,        Farbtonkanal,       Wertkanal
#Anschließend legen wir einen Schwellenwert für den Farbtonkanal fest, 
#um die Tasse vom Hintergrund zu trennen:

hue_threshold = 0.04
binary_img = hue_img > hue_threshold

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(16, 4))

ax0.hist(hue_img.ravel(), 512)

ax0.set_title("Histogram des hue-Kanals  mit Schwellenwerte")

ax0.axvline(x=hue_threshold, color='r', linestyle='dashed', linewidth=2)            
ax0.set_xbound(0, 0.2)                              #   12
ax1.imshow(binary_img)
ax1.set_title("Hue-thresholded image")
ax1.axis('off')

fig.tight_layout()
 

fig, ax0 = plt.subplots(figsize=(6, 3))

value_threshold = 0.4           #hier     Schwellenwert verändert
binary_img = (hue_img > hue_threshold) | (value_img < value_threshold)

ax0.imshow(binary_img)
ax0.set_title("Hue and value thresholded image")
ax0.axis('off')

fig.tight_layout()
plt.show()



Antworten