2019年11月26日 星期二

IOTESP8266架構學習

ESP8266012E
c
#include <stdio.h>
int main
{
  int a;
  a=30;

while(true)
  {
      printf("%d\n",a);
  }
   return 0;
}
arduino1.8.10
#include "Arduino.h"
void setup()
{
  [程式區塊]
}
 void loop()
{
   [程式區塊]
}
(1)只執行一次,變數初始值設定,腳位模式設定,運算一次的邏輯-->檔名.ino-->檔名.hex
(2)無限循環,無線訊號傳送,反覆運行的邏輯
++++++++++++++++++++++++++

wifibasic
#include<ESP8266WiFi.h>
#include<ESP8266WebServer.h>

ESP8266WebServer server(80);
char ssid[]="bsnet-1";
char pass[]="062230542";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",fun1);
 
  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    Serial.println();
    server.send(200,"text/html","Hello Webserver");
}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
======================
wifi

   begin()
webserver-----------○localIP
伺服器啟動
       ||
     on()-------GET---> / --->send()
                                   /led1-->send()     HMI
                                   /led2-->send()
                       brower  http://

++++++++++++++++++==
#include<ESP8266WiFi.h>
#include<ESP8266WebServer.h>

ESP8266WebServer server(80);
char ssid[]="bsnet-1";
char pass[]="062230542";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",fun1);
  server.on("/led1",fun2);
  server.on("/led2",fun3);
  server.on("/led3",fun4);
    
  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    Serial.println();
    server.send(200,"text/html","Hello Webserver");
}
void fun2()
{
    Serial.println();
    server.send(200,"text/html","LED1 ON");
}
void fun3()
{
    Serial.println();
    server.send(200,"text/html","LED2 ON");
}
void fun4()
{
    Serial.println();
    server.send(200,"text/html","LED3 ON");
}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
http://192.168.0.152/led1
+++++++++++++++++++++++++++++
<style>
#bt1,#bt2,#bt3,#bt4,#bt5
{
 background-color:#FCF;
 height:50px;
}
</style>
<script language="javascript" src="jquery-3.4.1.min.js"></script>
<script language="javascript">
function fun1()
{
$.get("http://192.168.0.152/led1",{},function(data)
{
alert(data);
});
}
function fun2()
{
$.get("http://192.168.0.152/led2",{},function(data)
{
alert(data);
});
}
function fun3()
{
$.get("http://192.168.0.152/led3",{},function(data)
{
alert(data);
});
}
function fun4()
{
$.get("http://192.168.0.152/allon",{},function(data)
{
alert(data);
});
}
function fun5()
{
$.get("http://192.168.0.152/alloff",{},function(data)
{
alert(data);
});
}
</script>
<body>
<input type="button" id="bt1" name="btn" value="LED1" onclick="fun1()"  />
<input type="button" id="bt2" name="btn" value="LED2" onclick="fun2()"  />
<input type="button" id="bt3" name="btn" value="LED3" onclick="fun3()" />
<input type="button" id="bt4" name="btn" value="ALL ON" onclick="fun4()"  />
<input type="button" id="bt5" name="btn" value="ALL OFF" onclick="fun5()" />
</body>
++++++++++++++++++++++++++++++++++++++++++++++++++++++
char ssid[]="bsnet-1";
char pass[]="062230542";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/led1",fun1);
  server.on("/led2",fun2);
  server.on("/led3",fun3);
  server.on("/allon",fun4);
  server.on("/alloff",fun5);
 
  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    Serial.println("1");
    server.send(200,"text/html","LED1 ON");
}
void fun2()
{
    Serial.println("2");
    server.send(200,"text/html","LED2 ON");
}
void fun3()
{
    Serial.println("3");
    server.send(200,"text/html","LED3 ON");
}
void fun4()
{
    Serial.println("4");
    server.send(200,"text/html","ALL ON");
}
void fun5()
{
    Serial.println("5");
    server.send(200,"text/html","ALL OFF");
}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
#http://192.168.0.152/led1
===================

function fun1(x)
{
$.get("http://192.168.0.152/"+x,{},function(data)
{
alert(data);
});
}


</script>
<body>
<input type="button" id="bt1" name="btn" value="LED1" onclick="fun1('led1')"  />
<input type="button" id="bt2" name="btn" value="LED2" onclick="fun1('led2')"  />
<input type="button" id="bt3" name="btn" value="LED3" onclick="fun1('led3')" />
<input type="button" id="bt4" name="btn" value="ALL ON" onclick="fun1('allon')"  />
<input type="button" id="bt5" name="btn" value="ALL OFF" onclick="fun1('alloff')" />
</body>
======================
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",HTTP_POST,fun1);

  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    String s=server.arg("t1");
    Serial.println(s);
    server.send(200,"text/html","Success");
}


void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
=========
<style>
#bt1,#bt2,#bt3,#bt4,#bt5
{
 background-color:#FCF;
 height:50px;
}
</style>
<script language="javascript" src="jquery-3.4.1.min.js"></script>
<script language="javascript">
function fun1()
{
$.post("http://192.168.0.152/",{t1:1},function(data)
{
alert(data);
});
}
function fun2()
{
$.get("http://192.168.0.152/",{t2:2},function(data)
{
alert(data);
});
}
function fun3()
{
$.get("http://192.168.0.152/",{t3:3},function(data)
{
alert(data);
});
}
function fun4()
{
$.get("http://192.168.0.152/",{t3:4},function(data)
{
alert(data);
});
}
function fun5()
{
$.get("http://192.168.0.152/",{t5:5},function(data)
{
alert(data);
});
}
</script>
<body>
<input type="button" id="bt1" name="btn" value="LED1" onclick="fun1()"  />
<input type="button" id="bt2" name="btn" value="LED2" onclick="fun2()"  />
<input type="button" id="bt3" name="btn" value="LED3" onclick="fun3()" />
<input type="button" id="bt4" name="btn" value="ALL ON" onclick="fun4()"  />
<input type="button" id="bt5" name="btn" value="ALL OFF" onclick="fun5()" />
</body>
================
ESP8266WebServer server(80);
char ssid[]="bsnet-1";
char pass[]="062230542";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",HTTP_POST,fun1);

  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    String s=server.arg("t1");
    int pwms=s.toInt();
    Serial.println(s);
    server.send(200,"text/html",s+":pwM值執行成功");
}


void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
==================
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
</head>
<script language="javascript" src="jquery-3.4.1.min.js"></script>
<script language="javascript">
function fun1()
{
var qs=document.getElementById("t1").value;
if (qs !="")
{
if (parseInt(qs)>=0  && parseInt(qs)<=255)
{
$.post("http://192.168.0.153/",{t1:qs},function(data)
{
$("#dv1").text("");
$("#dv1").text(data);
});
}
else
{
alert("請輸入0_255數值");
document.getElementById("t1").value="";
document.getElementById("t1").focus();

}
}
else
{
alert("不可為空請輸入0_255數值,");
}

}
function fun2()

document.getElementById("t1").value="";
$.post("http://192.168.0.153/",{t1:0},function(data)
{
$("#dv1").text("");
$("#dv1").text("無PWM值輸入");
});

}
</script>
<body>
<table width="200" height="200">
<tr>
<td>PWM值:</td>
<td><input type="text" id="t1" width="50"/>
</td>
</tr>
<tr>
<td height="73"><input type="button" id="bt1" name="btn" value="傳送" onclick="fun1()"  /></td>
<td><input type="button" id="bt2" name="btn" value="清除" onclick="fun2()"  /></td></tr>
<td colspan="2">
<div id="dv1"></div>
</td>
</table>
</body>
</html>
================
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
</head>
<script language="javascript" src="jquery-3.4.1.min.js"></script>
<script language="javascript">
function fun1()
{
var sv2=document.getElementById("slider1").value;
document.getElementById("t1").value=sv2;

if (sv2 !="")
{

$.post("http://192.168.0.153/",{t1:qs},function(data)
{
$("#dv1").text("");
$("#dv1").text(data);
});

}

}
function fun2()

document.getElementById("t1").value="";
$.post("http://192.168.0.153/",{t1:0},function(data)
{
$("#dv1").text("");
$("#dv1").text("無PWM值輸入");
});

}
</script>
<body>
<table width="200" height="200" border="1">
<tr>
<td>馬達一:</td>
<td><input type="range" min="0" max="100" value="0" class="slider" id="slider1"></td>
<td><input type="text" id="t1" width="50" onchange="fun1()"/>
</td>
</tr>
<tr>
<td>馬達二:</td>
<td><input type="range" min="0" max="100" value="0" class="slider" id="slider2"></td>
<td><input type="text" id="t2" width="50" onchange="fun2()"/>
</td>
</tr>
<tr>
<td>馬達三:</td>
<td><input type="range" min="0" max="100" value="0" class="slider" id="slider3"></td>
<td><input type="text" id="t3" width="50" onchange="fun3()"/>
</td>
</tr>
<tr>
<td>馬達四:</td>
<td><input type="range" min="0" max="100" value="0" class="slider" id="slider4"></td>
<td><input type="text" id="t4" width="50"/ onchange="fun4()">
</td>
</tr>
<tr>
<td colspan="3" align="center"><input type="button" id="bt1" name="btn" value="歸零"  onclick="fu5()"  /></td>
</tr>
<td colspan="3">
<div id="dv1"></div>
</td>
</table>
</body>
</html>
===
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",HTTP_POST,fun1);
  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    String s=server.arg("t1");
    int ch=s.toInt();
    if (ch==1))
    {
      int sv1=server.arg("t2").toInt();
      Serial.println("1:"+(s);
      server.send(200,"text/html","伺服馬達一執行"+(String)sv1+"度成功");
    }
}


void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
++++++++++++++++++++++++++
var url="";
function funload()
{
document.getElementById("uconn1").disabled=true;
}
function funconn()
{
url="http://"+document.getElementById("ip1").value;
document.getElementById("ip1").disabled=true;
document.getElementById("conn1").disabled=true;
document.getElementById("uconn1").disabled=false;
}
function funuconn()
{
url="";
document.getElementById("ip1").value="";
}

function fun1()
{
var ipa=document.getElementById("ip1").value;
if (ipa=="")
{
alert("請輸入IP位址");
document.getElementById("t1").value="";
}
else
{
var sv1=document.getElementById("slider1").value;
document.getElementById("t1").value=sv1;

if (sv1 !="")
{

$.post("http://192.168.0.153/",{t2:1,t1:sv1},function(data)
{
$("#sp1").text("");
$("#sp1").text(data);
});

}
}
}
---------------------
<body onload="funload()">
<table width="200" height="200" border="1">
<tr>
<td>WiFiIp:</td>
<td colspan="2"><input type="text" id="ip1" /></td>
</tr>
<tr>
<td><input type="button" id="conn1" value="連線" onclick="funconn()" /></td>
  <td><input type="button" id="uconn1" value="斷線" onclick="funuconn" /></td>
</tr>
<tr>
=====================================
var time;
var i=1;
function fun1()
{
var t=document.getElementById("a1").innerHTML;
if (t=="啟動")
{
time=setInterval(fun2,1000);
document.getElementById("a1").innerHTML="修止"
}
else
{
clearInterval(time);
document.getElementById("a1").innerHTML="啟動";
}

}
function fun2()

document.getElementById("sp1").innerHTML=i;
i=i+1;
if (i>=10)
{
i=1;
}


}
</script>
<body>
<a href="javascript:void;" id="a1"  onclick="fun1()" >啟動</a>
<p></p>
<span id="sp1>"</span>
</body>
</html>
++++++++++++++++++++++++++++++++++
7
#include<ESP8266WiFi.h>
#include<ESP8266WebServer.h>

ESP8266WebServer server(80);
char ssid[]="bsnet-1";
char pass[]="062230542";
int count=0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",HTTP_POST,fun1);
  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
    
    String s=server.arg("t1");
    int p=s.toInt();
    
    if (p==1)
    {
      count=count+1;
      if (count>=10)
      {
        count=0;
      }
      Serial.println(count);
      server.send(200,"text/html",(String)count+"_類比值讀取成功");
    }
    else
    {
      server.send(200,"text/html","類比值讀取不進行");
    }
}


void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
+++++++++++++++++++++++++++++
<script language="javascript" src="jquery-3.4.1.min.js"></script>
<script language="javascript">
var time;
var i=1;
function fun0()
{
time=setInterval(fun1,1000);
}
function fun1()
{   
$.post("http://192.168.0.153/",{t1:1},function(data)
{
var tdata=data.split("-")
$("#sp1").text(tdata[0]);
$("#sp2").text(tdata[1]);
});
}
</script>
<body onload="fun0()">
類比值;<span id="sp1" ></span>
<p></p>
狀態;<span id="sp2"></span>
</body>
+++++++++++++++++++++++++++

8
#include<ESP8266WiFi.h>
#include<ESP8266WebServer.h>

ESP8266WebServer server(80);
char ssid[]="bsnet-1";
char pass[]="062230542";
int count=0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",HTTP_POST,fun1);

  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
 
    String s=server.arg("t1");
    int p=s.toInt();
    int rv=random(0,9);
    Serial.println(rv);
    server.send(200,"text/html",rv);
 
}


void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
+++++++++++++++++++++++++++++
12/05
hmi ui 引入
Javascript
jquery           ]==> UI==>body==>Javacript自訂程式==>設計
css 
++++++++++++++++
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
</head>
<link rel="stylesheet" href="./hmili/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="./jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="./hmili/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="./hmili/jqwidgets/jqxdraw.js"></script>
<script type="text/javascript" src="./hmili/jqwidgets/jqxknob.js"></script>
<script type="text/javascript">
        $(document).ready(function () {

            $('#knob').jqxKnob({
                value: 60,
                min: 0,
                max: 255,
                startAngle: 150,
                endAngle: 510,
                snapToStep: true,
                rotation: 'clockwise',
                style: { stroke: '#dfe3e9', strokeWidth: 3, fill: { color: '#fefefe', gradientType: "linear", gradientStops: [[0, 1], [50, 0.9], [100, 1]] } },
                marks: {
                    colorRemaining: '#333',
                    colorProgress: '#333',
                    type: 'line',
                    offset: '71%',
                    thickness: 1,
                    size: '6%',
                    majorSize: '9%',
                    majorInterval: 10,
                    minorInterval: 2
                },
                labels: {
                    offset: '88%',
                    step: 10
                },
                progressBar: {
                    style: { fill: { color: '#00a644', gradientType: "linear", gradientStops: [[0, 1], [50, 0.9], [100, 1]] }, stroke: '#00a644' },
                    background: { fill: { color: '#ff8b1e', gradientType: "linear", gradientStops: [[0, 1], [50, 0.9], [100, 1]] }, stroke: '#ff8b1e' },
                    size: '9%',
                    offset: '60%'
                },
                spinner: {
                    style: { fill: { color: '#00a4e1', gradientType: "linear", gradientStops: [[0, 1], [50, 0.9], [100, 1]] }, stroke: '#00a4e1' },
                    innerRadius: '45%', // specifies the inner Radius of the dial
                    outerRadius: '60%', // specifies the outer Radius of the dial
                    marks: {
                        colorRemaining: '#fff',
                        colorProgress: '#fff',
                        type: 'line',
                        offset: '46%',
                        thickness: 2,
                        size: '14%',
                        majorSize: '14%',
                        majorInterval: 10,
                        minorInterval: 10
                    },
                },
                dial:
                    {
                        style: { fill: { color: '#dfe3e9', gradientType: "linearHorizontal", gradientStops: [[0, 0.9], [50, 1], [100, 1]] }, stroke: '#dfe3e9' },
                        innerRadius: '0%', // specifies the inner Radius of the dial
                        outerRadius: '45%'
                    },
                pointer:
                    {
                        type: 'circle',
                        style: { fill: '#ef6100', stroke: '#ef6100' },
                        size: '5%',
                        offset: '38%',
                        thickness: 20
                    }
            });

            var lastValue;
            var newValue = 0;
            var min = 0;
            var max = 255;
            $('#knob').on('change', function (event) {
                lastValue = newValue;
                newValue = event.args.value;
                if (newValue >= min && newValue <= min + 10 && lastValue <= max && lastValue >= max - 10){
                    min = max;
                    max += 100;
                    $('#knob').jqxKnob({ value: max, max: max, min: min });
                } else if (newValue >= max - 10 && newValue <= max && lastValue >= min && lastValue <= min + 10){
                    max = min;
                    min -= 100;
                    $('#knob').jqxKnob({ value: min, min: min, max: max });
                }

document.getElementById("sp1").innerHTML=newValue;
            });
$("#bt1").click(function()
{
var rv=document.getElementById("sp1").innerHTML;
alert(rv);
$.post("http://192.168.0.113/",{t1:1,t2:rv},function(data)
{
//$("#sp2").text("");
$("#sp2").text(data);
});
});
        });
function fun2()
{



$.post("http://192.168.0.113/",{t1:1,t2:rv},function(data)
{
$("#sp2").text("");
$("#sp2").text(data[1]);
});

}
</script>
<body class='default'>
<div id='knob'>
</div>
<p>
<table width="400" rules="rows">
<tr>
<td >
調整值 :</td><td ><span id="sp1" size="30" ></span></td>
<td> <input type="button"  id="bt1" value="確定" onclick="fun1" />
</td>
</tr>
<tr>
<td colspan="3" >
狀態列:<span id="sp2"  >&nbsp;&nbsp;</span>脈衝值瀉入成功
</td>
</tr>
</table>
</body>
</html>
___________________
  #include<ESP8266WiFi.h>
#include<ESP8266WebServer.h>

ESP8266WebServer server(80);
char ssid[]="bsnet-1";
char pass[]="062230542";
int count=0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  delay(3000);

  server.on("/",HTTP_POST,fun1);

  server.begin();
  Serial.println();
  Serial.println(WiFi.localIP());
}

void fun1()
{
   
    String s=server.arg("t1");
    int p=s.toInt();
    if (p==1)
    {
      int rv=server.arg("t2").toInt();
      Serial.println(rv);
      server.send(200,"text/html",(String)rv+"-脈衝值傳送成功");
   
    }
    //int rv=random(0,9);
    else
    {
      server.send(200,"text/html","未進行脈衝值傳送成功");
      }
 
   
}


void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}
________________________
        

2019年11月15日 星期五

爬蟲語言學習

11/16


爬蟲語言架構



安裝python3.6 pyzoIDE pip 安裝10個套件
numpy 矩陣運算
matplotlib視覺化圖片輸出
SciPy 資料科學    以上三個補助運算
beautifulsoup4 爬蟲語言html/css  靜態語言<a><span><div.<td>等
Selenium動態語言html/表單Javascipt:Json,xml
Scrapy網頁框架Vue.js 以上三個爬蟲套件 DOM,Jquary Http:post get
Pandas圖表資料處理1.瀏覽2.查詢系統3.曾刪除修4.模糊查詢5.統計和分析6.決策
Seaborn/Bokeh視覺化輸出 圖表和文字
mysql-connector-python 資料庫連線mysqlserver
Firebase Google雲端資料庫-大數據分析平台GA

---------------------------------------
在C設一資料夾python36安裝python3.6
               資料夾Bigdataproject1放相關學習檔案\
*************************************************
python基礎
間隔輸出
print(value, ..., sep=' ', end='\n', file=sys.stdout)

  • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
  • sep -- 用来间隔多个对象,默认值是一个空格。
  • end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
  • file -- 要写入的文件对象。
  • flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。
input()可以指定提示文字,使用者輸入的文字則以字串傳回(Python 2.7的輸入是使用raw_input()
+++++++++++++++++++++++++++
12/06
while
----------------
while True:
#ch=0
n=int(input("請輸入一個數值:"))

total=1
i=1

while (i<=n):


total *=i
i=i+1
print(total)
ch=int(input("請選擇:(1)繼續(2)停止"))
if (ch==2):
break
---------------------------------------
list
基本概念
常用函數(一)
1.元素相加 sum(串列名稱)
1.自計算
a=[12,56,99,21,52]

len1=len(a)
total=0

for i in range(len1-1,0-1,-1):
     total +=a[i]


print("total:",total)
----------------------------------------
2.a=[12,56,99,21,52]
total=sum(a)
print("total:",total)
2.最大值max()

3.最小值 min()
4.正排序 sorted()
a=[12,56,99,21,52]

len1=len(a)
c=sorted(a)
for i in range(0,len1):

print(c[i])
5.逆排序 sorted(,reverse=True)
a=[12,56,99,21,52]

len1=len(a)
c=sorted(a,reverse=True)
for i in range(0,len1):
print(c[i])

-----------------------
6.判斷指定元素是在串列中
if 元素 in 串列名稱:
   [程式區塊]
a=[10,20,30,40,60]
qp=30
x=False
if qp in a:
    x=True
if x==True:
    print("存在")
else:

    print("不存在")
------------------------------
常用函數(一)
1.新增
物件.append(值)
mylist1=[]

mylist1.append("java")
mylist1.append("javascript")
mylist1.append("delphi")
mylist1.append("c++")
mylist1.append("jquery")

for i in mylist1:

print(i)
2.新增(插入)
物件.insert(索引位置,值)
mylist1=[]

mylist1.append("java")
mylist1.append("javascript")
mylist1.append("delphi")
mylist1.append("c++")
mylist1.append("jquery")
mylist1.insert(2,"php")

for i in mylist1:

print(i)
3.數量
物件.count(值)
data=["java","javascript","delphi","c++","jquery"]
qp="java"

c=data.count(qp)

print("[{0}]在串列中出現[{1}]次".format(qp,c))
4.索引位置
  物件.index(值)
5.刪除:
 物件.remove(值)
------------------------------
11/13
data=["java","javascript","delphi","c++","jquery"]
qp="javascript"

data.remove(qp)
for i in data:

print(i)
______
lista=[[10,20],[30,40],[50,60]]

yl=len(lista)
xl=len(lista[0])
print("y軸長度:{0}".format(yl))
print("x軸長度:{0}".format(xl))

print(lista[0][0])
print(lista[0][1])
print(lista[1][0])
print(lista[1][1])
print(lista[2][0])
print(lista[2][1])

for i in range(0,yl):
for j in range(0,xl):

print("lista[{0}][{1}]={2}".format(i,j,lista[i][j]))
-------------------------------------------------------
tuple
tup1=(12,67,88,32,11)

len1=len(tup1)
print(len1)

for i in range(len1):

print("tup1({0})={1}".format(i,tup1[i]))
______________________________________
tup1=("java","javascript","delphi","c++","jquery")
list1=list(tup1)
list1.append("jsp")#先轉串列在加
len1=len(list1)

for i in range(0,len1):

print(list1[i])
#java
javascript
delphi
c++
jquery
jsp
_____________________

data=(("p1001","小明",60,70,80),
("p1002","小鈴",70,50,90),
("p1003","小童",23,60,80),
("p1004","小張",93,60,90),
("p1005","小金",70,56,86))

leny=len(data)
lenx=len(data[0])
p=0
k=False
while True:
ax=int(input("選單(1)總覽(2)查詢國文大於等於60(3)查詢英文小於等於60(4)學號查詢(5)完全結束:"))




if ax==1:
print("%s\t\t%s\t\t%s\t%s\t%s\t%s\t%s" % ("學號","姓名","國文","英文","數學","總分","平均"))
for i in range(0,leny):
total=data[i][2]+data[i][3]+data[i][4]
avg=total/3.0
print("%s\t%s\t\t%d\t%d\t%d\t%d\t%.2f" % (data[i][0],data[i][1],data[i][2],data[i][3],data[i][4],total,avg))


if ax==2:
for i in range(0,leny):
if data[i][2]>=60:
print("%s\t%s\t\t%d\t%d\t%d" % (data[i][0],data[i][1],data[i][2],data[i][3],data[i][4]))

if ax==3:
for i in range(0,leny):
if data[i][3]<60:
print("%s\t%s\t\t%d\t%d\t%d" % (data[i][0],data[i][1],data[i][2],data[i][3],data[i][4]))

if ax==4:
qpn=input("請輸入學號")
for i in range(0,leny):
if qpn==data[i][0]:
p=i
k=True
break
if k==True:
print("%s\t%s\t\t%d\t%d\t%d" % (data[i][0],data[i][1],data[i][2],data[i][3],data[i][4]))
else:
print("查無此資料")
print(ax)
if ax==5:
break




------------------------------

12/20
dict
data={"Java":350,"c++":260,"delphi":300,"c":100,"Javascript":70}

len1=len(data)
print(len1)
print(data["Java"])
print(data["c++"])

k=list(data.keys())
print(k)
for i in range(0,len1):

print(k[i])
#5
350
260
['Java', 'c++', 'delphi', 'c', 'Javascript']
Java
c++
delphi
c
Javascript
+++++++++++++++++++++++
price=[35,78,90,12,88]
fruits=("李子","水蜜桃","西瓜","哈密瓜","文旦")

len1=len(price)
fdata={}
for i in range(0,len1):
fdata[fruits[i]]=price[i]
k=list(fdata.keys())
v=list(fdata.values())
len1=len(k)
for i in range(0,len1):



    print("%s===>%d" % (k[i],v[i]))
________________________________
dict1={"程式":["Java","c++","delphi"]}
list1=dict1["程式"]
for i in list1:

print(i)
---------------------------------------
12/27
dictex2.py
dict1={"程式":["java","c","javascript"],
"美工":["photoshop","illustrator","cordraw"],
"系統":["dos","window","mac"]}

len1=len(dict1)
key1=list(dict1.keys())
data1=list(dict1.values())

for i in range(0,len1):
print(key1[i])

d=data1[i]
lend=len(d)
for j in range(0,lend):
print(d[j],end="\t")


print()
---------
#程式
java c javascript
美工
photoshop illustrator cordraw
系統
dos window mac
========================

python函數
函數一:  全域變數
def  函數名稱():
       [程式區塊]
 
函數名稱()
def chin():
print("函數架構一")


chin()

函數二:   區域變數
def  函數名稱(參數一,參數二):
       [程式區塊]
   
函數名稱(引數1,引數2)
def chinfun2(str):
       print(str)


chinfun2("函數架構二")

函數三:
def  函數名稱():
       [程式區塊]
       return  回傳結果
接收回傳變數=函數名稱()
def chinfun3():
     return 300

x=chinfun3()

print(x)

函數四:
def  函數名稱(參數一,參數二)
       [程式區塊]
       return  回傳結果
接收回傳變數=函數名稱(引數1,引數2)
def chinfun4(x,y):
     total=x+y
     return total

if __name__=="__main__":
     sum=chinfun4(12,67)

     print(sum)

函數功能
1.功能整理
2.易於維修
3.模組程式發展
4.類別元件開發
5.系統架構

https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/374459/

python 主程式
if __name__=="__main__":
     [程式區塊]
----------------------------
批次傳值:
串列/元組/字典當引數傳值必須用相對應元件參數接收
def chinarray(sd):
     len1=len(sd)
     for j in range(len1):
          print(sd[j])

if __name__=="__main__":
      list1=[12,56,88,43,94]
      chinarray(list1)

批次回傳值:

串列/元組/字典當批次回傳結果必須用相對應元件接收回傳變數
def chinarray3():
     list1=[45,78,12,34,99]
     return list1

if __name__=="__main__":
    sd=chinarray3()
    len1=len(sd)
    for h in range(len1):
        print(sd[h])
----------------------
-
----------------------

def input1():
a=int(input("數值一:"))
b=int(input("數值二:"))
sum=logic1(a,b)
show1(a,b,sum)

def logic1(x,y):
total=x+y
return total

def show1(a,b,c):
print("{0}+{1}={2}".format(a,b,c))
exitfun1()

def exitfun1():
x=int(input("(1)繼續執行(2)完全離開"))
if x==1:
input1()
elif x==2:
quit()
else:
exitfun1()


if __name__=="__main__":
input1()
_______________________________

import requests

r=requests.get("http://192.168.0.53/webproject1/chinjung1.txt")
r.encoding="utf-8"

if r.status_code==requests.codes.ok:

print(r.text)
--------------
import requests

r=requests.get("http://192.168.0.53/webproject1/chinjung2.txt")
r.encoding="utf-8"

if r.status_code==requests.codes.ok:
   dat=r.text
   print(dat)
   list1=dat.split(",")
   len1=len(list1)
   j=1
  for i in range(0,len1,1):
       print(j,"==>",list1[i])
       j=j+1
_____________
#
程式設計,美工設計,文書設計,系統設計,網頁設計

1 ==> 程式設計
2 ==> 美工設計
3 ==> 文書設計
4 ==> 系統設計

5 ==> 網頁設計
--------------------------------
import requests

r=requests.get("http://192.168.0.53/webproject1/chinjung3.txt")
r.encoding="utf-8"

if r.status_code==requests.codes.ok:
   dat=r.text
   print(dat)
   list2=dat.split("\r\n")
   len1=len(list2)
   print()

for i in range(0,len1,1):
   kdata=list2[i]
   list3=kdata.split(",")
   len2=len(list3)
  for j in range(0,len2,1):
     print(list3[j])
  print()


----------------------------
1/10
import csv

list1=[[12,34,56],[32,54,21],[56,87,43]]
filename="csvfile1.csv"
with open(filename,"w+",newline="") as f:
writer=csv.writer(f)
writer.writerow(["data1","data2","data3"])
for row in list1:
writer.writerow(row)


f.close()
___________________
import csv

filename="csvfile1.csv"
with open(filename,"r") as f:
data=csv.reader(f)
for row in data:
print(",".join(row))


f.close()
___________________
Json:https://www.runoob.com/python/python-json.html
格式:{key1:value1,key2:value2,key3:value3,.....}
函數庫:import json
載入json:方法一:json.dumps()
                   方法二:json.loads()
一般取值:元件名稱["key"]
批次取值:元件名稱.key()
                    元件名稱.values()


import json

data=[{'a':1,'b':2,'c':3,'d':4,'e':5}]
json=json.dumps(data)

print(json)
#[{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
_________
import json

jsonData='{"a":1,"b":2,"c":3,"d":4,"e":5}'
text=json.loads(jsonData)

print(text)
#{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
---------------------
import json

jsonData='{"a":1,"b":2,"c":3,"d":4,"e":5}'
text=json.loads(jsonData)
print(text['a'])
print(text['b'])
print(text['c'])
print(text['d'])

print(text['e'])
#1
2
3
4
5
-----------
import json

jsonData='{"a":1,"b":2,"c":3,"d":4,"e":5}'
text=json.loads(jsonData)
list1=list(text.keys())#先轉為串列
len1=len(list1)
list2=list(text.values())
len2=len(list2)
for i in range(0,len1,1):

print(list1[i],"==>",list2[i])
#a ==> 1
b ==> 2
c ==> 3
d ==> 4
e ==> 5
-----------------
chinjung1.json
{"a":100,
 "b":200,
 "c":300,
 "d":400,
 "e":500
}
json5.py
import requests
import json

r=requests.get("http://192.168.0.53/webproject1/chinjung1.json")
r.encoding="utf-8-sig"

if r.status_code==requests.codes.ok:
   dat=r.text
   text=json.loads(dat)
   list1=list(text.keys())
   len1=len(list1)
   list2=list(text.values())
   len2=len(list2)
  for i in range(0,len1,1):

       print(list1[i],"==>",list2[i])
#a ==> 100
b ==> 200
c ==> 300
d ==> 400
e ==> 500
----------------------------------------------

0117
import sys

f=open("jungdb2.txt","a")
f.write("學習python邁向人工智慧之路")
print("%s" % "資料寫入成功")

f.close()
_______
f=open("jungdb2.txt","a")
f.write("\r\n學習c邁向嵌入應用系統之路")
print("%s" % "資料寫入成功")

f.close()
_________________
with open("jungdb2.txt","r") as f:
data=f.readline()
print("%s" % data)


f.close
___________________
with open("jungdb2.txt","r") as f:
data=f.readlines()
print("%s" % data)

len1=len(data)
print(len1)
print(data[0])
print(data[2])

f.close
__________________
from urllib.request import urlopen
#from bs4 import BeautifulSoup

print("success")

_______________
from urllib.request import urlopen
#from bs4 import BeautifulSoup

print("success")

__________________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://192.168.0.53/webproject1/chin2.html").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")

print(soup.title.text)
________________________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://192.168.0.53/webproject1/chin2.html").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")

print(soup.font.text)
___________________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")

print(soup.title.text)
______________________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")

print(soup.ul.text)
#作品發表
文章
________________________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://192.168.0.53/webproject1/chin2.html").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")

print(soup.font.text)
_____
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://192.168.0.53/webproject1/wchin1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")

print(soup.p.text)
________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://192.168.0.53/webproject1/wchin1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")
kdata=soup.find_all("p")
print(kdata)
len1=len(kdata)
for i in range(0,len1,1):

print(kdata[i])
#[<p>程式設計</p>, <p>美工設計</p>, <p>繪圖設計</p>, <p>系統設計</p>, <p>資料庫設計</p>]
<p>程式設計</p>
<p>美工設計</p>
<p>繪圖設計</p>
<p>系統設計</p>
<p>資料庫設計</p>
_________________________
from urllib.request import urlopen
from bs4 import BeautifulSoup

html=urlopen("http://192.168.0.53/webproject1/wchin1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"html.parser")
kdata=soup.find_all("p")
print(kdata)
len1=len(kdata)
for i in range(0,len1,1):

print(kdata[i].text)
#[<p>程式設計</p>, <p>美工設計</p>, <p>繪圖設計</p>, <p>系統設計</p>, <p>資料庫設計</p>]
程式設計
美工設計
繪圖設計
系統設計
資料庫設計
------------------------
<body>
<a id="a1" href="javascript:void;">按扭驅動</a>
<p></p>
<a id="a2" href="javascript:void;">按扭驅動</a>
<p></p>
<div class="c1">程式設計</div>
<div class="c1">美工設計</div>
<div class="c1">系統設計</div>
<div class="c1">網頁設計</div>
<div class="c1">軟體設計</div>

</body>
-------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://192.168.0.53/webproject1/wchin4.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.find(id="a2")
print(kdata.string)
#按扭驅動
--------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://192.168.0.53/webproject1/wchin4.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.findAll(attrs={"class":"c1"})
len1=len(kdata)
print(len1)
for i in range(0,len1,1):
    print(kdata[i].string)
for i in range(0,len1,1):
    print(kdata[i].get_text())
#5
程式設計
美工設計
系統設計
網頁設計
軟體設計
程式設計
美工設計
系統設計
網頁設計
軟體設計
--------------------------------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select(".slide_nav li")
len1=len(kdata)
print(len1)
for i in range(0,len1,1):
print(kdata[i].string)

#5
本日精選總覽
最新作品
評議推薦
資深推薦
發表作品
----------------------------------------------
1/31
wchin3.html
<table border="2" width="500"><br />
<tr>
<td>編號</td>
<td>姓名</td>
<td>生日</td>
<td>血型</td>
<td>學歷</td>
</tr>
<tr>
<td>p1001</td>
<td>迪力熱巴</td>
<td>67/12/09</td>
<td>A</td>
<td>研究所</td>
</tr>
<tr>
<td>p1002</td>
<td>古力納札</td>
<td>71/12/09</td>
<td>O</td>
<td>大學</td>
</tr>
<tr>
<td>p1003</td>
<td>趙麗穎</td>
<td>69/10/09</td>
<td>B</td>
<td>研究所</td>
</tr>

</table>
-------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")

kdata=soup.select(".slide_nav li")
len1=len(kdata)
#print(len1)
for i in range(0,len1,1):

print(kdata[i].string)
#編號
姓名
生日
血型
學歷
p1001
迪力熱巴
67/12/09
A
研究所
p1002
古力納札
71/12/09
O
大學
p1003
趙麗穎
69/10/09
B
研究所
----------------------------------
Beautiful --> pandas                --> matplotlib
爬取資料    處理資料>正規化    繪圖模組(視覺化輸出)
                   (瀏覽 查 詢 過濾 新增刪除修改 匯出匯入)

基礎pandas(一)
1.引入函數庫:
import pandas as pd
2.
字典-->DataFrame -->   輸出
pd.DataFrame(字典來源資料)
pd.DataFrame(字典來源資料,columns=["欄名1","欄名2","欄名3","欄名4","欄名5"])
__________________________
11-1
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://192.168.0.53/webproject1/wchin3.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.find_all("td")
#print(kdata)
len1=len(kdata)
id1=[]
name1=[]
birth1=[]
blood1=[]
school1=[]
for i in range(0,len1,5):
if i>=5:
id1.append(kdata[i].text)
name1.append(kdata[i+1].text)
birth1.append(kdata[i+2].text)
blood1.append(kdata[i+3].text)
school1.append(kdata[i+4].text)
len2=len(blood1)
print("編號",end="\t\t")
print("姓名",end="\t\t")
print("生日",end="\t\t")
print("血型",end="\t\t")
print("學歷",end="\t\t")
print()
for k in range(0,len2,1):
print(id1[k].strip(),end="\t")
print(name1[k].strip(),end="\t")
print(birth1[k].strip(),end="\t")
print(blood1[k].strip(),end="\t")

print(school1[k].strip(),end="\t")
#編號 姓名 生日 血型 學歷
p1001 迪力熱巴 67/12/09 A 研究所
p1002 古力納札 71/12/09 O 大學
p1003 趙麗穎 69/10/09 B 研究所
>>>
_________________________
11-3
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml
import pandas as pd

html=urlopen("http://192.168.0.53/webproject1/wchin3.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.find_all("td")
#print(kdata)
len1=len(kdata)
id1=[]
name1=[]
birth1=[]
blood1=[]
school1=[]
for i in range(0,len1,5):
if i>=5:
id1.append(kdata[i].text.strip())
name1.append(kdata[i+1].text.strip())
birth1.append(kdata[i+2].text.strip())
blood1.append(kdata[i+3].text.strip())
school1.append(kdata[i+4].text.strip())
len2=len(blood1)
sourse={"id":id1,"name":name1,"birth":birth1,"blood":blood1,"school":school1}
ds=pd.DataFrame(sourse,columns=["id","name","birth","blood","school"])
print(ds)
rowlen=ds.shape[0]
collen=ds.shape[1]
print("列數:",rowlen)
print("欄數:",collen)

ds.to_csv("lochinjung.csv")
#id name birth blood school
0 p1001 迪力熱巴 67/12/09 A 研究所
1 p1002 古力納札 71/12/09 O 大學
2 p1003 趙麗穎 69/10/09 B 研究所
列數: 3
欄數: 5

_________________________________

______________________
<table border="2" width="500"><br />
<tr>
<td>編號</td>
<td>姓名</td>
<td>生日</td>
<td>血型</td>
<td>學歷</td>
    <td>畢業總分數</td>
</tr>
<tr>
<td>p1001</td>
<td>迪力熱巴</td>
<td>67/12/09</td>
<td>A</td>
<td>研究所</td>
    <td>78</td>
</tr>
<tr>
<td>p1002</td>
<td>古力納札</td>
<td>71/12/09</td>
<td>O</td>
<td>大學</td>
    <td>56</td>
</tr>
<tr>
<td>p1003</td>
<td>趙麗穎</td>
<td>69/10/09</td>
<td>B</td>
<td>研究所</td>
    <td>98</td>
</tr>
_________________________
11-4
import lxml
import pandas as pd
import matplotlib.pyplot as plt

html=urlopen("http://192.168.0.53/webproject1/wchin3_3.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.find_all("td")
#print(kdata)
len1=len(kdata)
id1=[]
name1=[]
birth1=[]
blood1=[]
school1=[]
total1=[]
for i in range(0,len1,6):
if i>=6:
id1.append(kdata[i].text.strip())
name1.append(kdata[i+1].text.strip())
birth1.append(kdata[i+2].text.strip())
blood1.append(kdata[i+3].text.strip())
school1.append(kdata[i+4].text.strip())
total1.append(kdata[i+5].text.strip())
len2=len(blood1)
sourse={"id":id1,"name":name1,"birth":birth1,"blood":blood1,"school":school1,"total":total1}
ds=pd.DataFrame(sourse,columns=["id","name","birth","blood","school","total"])
print(ds)
rowlen=ds.shape[0]
collen=ds.shape[1]
print("列數:",rowlen)
print("欄數:",collen)
ds.to_csv("lochinjung.csv")
a=int(ds["total"][0])
b=int(ds["total"][1])
c=int(ds["total"][2])
data=[a,b,c]
plt.bar([1,2,3],data)
plt.yticks([0,10,20,30,40,50,60,70,80,90,100])

plt.show()
#id name birth blood school total
0 p1001 迪力熱巴 67/12/09 A 研究所 78
1 p1002 古力納札 71/12/09 O 大學 56
2 p1003 趙麗穎 69/10/09 B 研究所 98
列數: 3
欄數: 6
__________________________
207
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://192.168.0.53/webproject1/wchin4.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.find(text="系統設計")
print(kdata.parent.name)

#div
-------------------------------------------
向下走訪
選擇器:
1.元件.select("#id"):選擇ID定位
2.children:子元件
NavigableString:
from bs4.element import NavigableString

3.for i in tdata.children:
       print(type(i))a
a. type(i)印出元件
b. i.name元件名稱
c. i,text元件內容
4.排除NavigableString
if not isinstance(i,NavigableString):
     print(i.name)
5.i.元件名稱.text  子元件(內層元件)
i.div.text
i.span.text
________________________
<div id="q2">
<ul class="answer">
    <li><div>程式設計</div><span>3000</span></li>
        <li><div>美工設計</div><span>4000</span></li>
        <li><div>網頁設計</div><span>5000</span></li>
    </ul>
</div>
_________________________
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml

html=urlopen("http://192.168.0.53/webproject1/wormdata1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#q2")
tdata=kdata[0].ul
len1=len(tdata)
print(len1)

for i in tdata.children:

print(type(i))
#7
<class 'bs4.element.NavigableString'>
<class 'bs4.element.Tag'>
<class 'bs4.element.NavigableString'>
<class 'bs4.element.Tag'>
<class 'bs4.element.NavigableString'>
<class 'bs4.element.Tag'>
<class 'bs4.element.NavigableString'>
-----------------------------------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://192.168.0.53/webproject1/wormdata1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#q2")
tdata=kdata[0].ul
len1=len(tdata)
print(len1)

for i in tdata.children:
    if not isinstance(i,NavigableString):

          print(i.name)
#7
li
li
li

____________________________________
for i in tdata.children:
     if not isinstance(i,NavigableString):

          print(i.text)
#7
程式設計3000
美工設計4000
網頁設計5000
________________________________
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://192.168.0.53/webproject1/wormdata1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#q2")
tdata=kdata[0].ul
len1=len(tdata)
print(len1)

for i in tdata.children:
     if not isinstance(i,NavigableString):
             print(i.div.text)
             print(i.span.text)

#7
程式設計
3000
美工設計
4000
網頁設計
5000
___________________
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://192.168.0.53/webproject1/wormdata1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#q2")
tdata=kdata[0].ul


for i in tdata.parents:
print(i.name)

print()
for j in tdata.find_parents():
print(j.name)

#div
body
html
[document]

div
body
html
[document]

___________________
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://192.168.0.53/webproject1/wormdata1.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#q2")
tdata=kdata[0].ul.li

pdata=tdata.next_sibling.next_sibling
print(pdata.text)
cdata=pdata.next_sibling.next_sibling
print(cdata.text)

qdata=cdata.previous_sibling.previous_sibling
print(cdata.text)
udata=qdata.previous_sibling.previous_sibling
print(udata.text)


#美工設計4000
網頁設計5000
網頁設計5000
程式設計3000

_____________________
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#tab1")
tdata=kdata[0].ul
len1=len(tdata)
print(len1)

for i in tdata.children:
       if not isinstance(i,NavigableString):
           print(i.text)

#7
攝影基礎線上輕鬆學 (18主題)
全景&縮時攝影簡單學 (2主題)
鯊魚- 婚禮攝影技巧分享 (2主題)
人像外拍場景考量 (4主題)
運動攝影-快速上手 (3主題)
看更多>>
________________________
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select(".ul_wrapper")
tdata=kdata[0].ul

for i in tdata.children:
    if not isinstance(i,NavigableString):
        print(i.text)


----------------------
人像
秀展
風景
夜景
生態
飛羽
植物
美食
人文
建築
動物

教學
-------------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select(".copyright .clearfix")
tdata=kdata[0]

for i in tdata.children:
if not isinstance(i,NavigableString):
print(i.text)

kdata2=soup.select(".share")
tdata2=kdata2[0]

for j in tdata2.children:
if not isinstance(j,NavigableString):
print(j.text)

#行銷合作
廣告刊登
客服中心
迪希facebook粉絲團
迪希facebook粉絲團
-------------------------------
0214
<div id="total">
<div id="dv1">java</div>
    <div id="dv2">c++</div>
    <div id="dv3">jquery</div>
    <div id="dv4">javascript</div>
    <div id="dv5">html</div>
</div>
--------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://192.168.0.53/webproject1/wormdata3.html").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.find(id="total")
print(kdata.text)

cdata=kdata.next_element.next_element
print(cdata.text)
pdata=cdata.next_element.next_element
print(pdata)
tdata=pdata.next_element.next_element
print(tdata)

for i in kdata.next_elements:
if not isinstance(i,NavigableString):
print(i.name,"==>",i.text)

#java
c++
jquery
javascript
html

java


c++
div ==> java
div ==> c++
div ==> jquery
div ==> javascript
div ==> html
=======================
讀取線上圖片
kimg=urlopen(url)
info=kimg.read(1000)
size=size+len(info)
kimg.close()
儲存線上圖片
fp=open("filename","wb")
fp.w


----------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("http://www.dcview.com/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("#banner-fade")
tdata=kdata[0].ul
len1=len(tdata)
print(len1)

strimg=""
for i in tdata.children:
if not isinstance(i,NavigableString):
strimg=i.img.get("src")
print(strimg)

kimg=urlopen(strimg)
fp=open("image/chin2.jpg","wb")
size=0
while True:
info=kimg.read(1000)
if len(info)<1:
break
size=size+len(info)
fp.write(info)
fp.close()
kimg.close()

-------------------------
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import lxml

html=urlopen("https://okgo.tw/butyview.html/?id=3283").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select(".pic")
len1=len(kdata)
print(len1)

strimg=[]
for i in range(0,len1,1):
strimg.append(kdata[i].img.get('src'))

strimg2=[]
for k in range(0,len1,1):
lenk=len(strimg[k])
if lenk>25:
strimg2.append(strimg[k])
len2=len(strimg2)
print(len2)

for j in range(0,len2,1):
kimg=urlopen(strimg2[j])
fp=open("image2/chin.jpg"+str(j)+".jpg","wb")
size=0
while True:
info=kimg.read(1000)
if len(info)<1:
break
size=size+len(info)
fp.write(info)
fp.close()
kimg.close()
________________________
from bs4 import BeautifulSoup
from bs4.element import NavigableString
from urllib.request import urlopen
import lxml

s=""
html=urlopen("http://www.bsnet.com.tw/").read().decode("utf-8")
soup=BeautifulSoup(html,"lxml")
kdata=soup.select("table tr td img")
#print(kdata)
len1=len(kdata)
print(len1)

strimg=[]
for i in range(0,len1,1):
strimg.append("http://www.bsnet.com.tw/"+kdata[i].get('src'))

strimg2=[]
for t in range(0,len1,1):
str1=strimg[t]
#print(str[-3:1])
str2=str1[-3:]
if str2=="jpg":
strimg2.append(strimg[t])

len2=len(strimg2)
for j in range(0,len2,1):
kimg=urlopen(strimg2[j])
fp=open("image3/jung"+str(j)+".jpg","wb")
size=0
while True:
info=kimg.read(1000)
if len(info)<1:
break
size=size+len(info)
fp.write(info)

fp.close()

kimg.close()
#57
==================
0221
xpath:
1.函數庫:
from lxml import html
html.fromstring(urlopen)
=>kdata
kdata.xpath()[0]=>第一個元素

2.取得元素:
元件
3.元件‧tag
4.xpath為網頁結構路徑
++++++
1
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/wormdata3.html").read().decode("utf-8")
kdata=html.fromstring(h)

print(kdata)
#<Element html at 0x3e0c1d8>
+++++++++++++++++++
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/wormdata3.html").read().decode("utf-8")
kdata=html.fromstring(h)
#print(kdata)

for i in kdata.getchildren():

print(i)
#<Element head at 0x4024e08>
<Element body at 0x4024ea8>
+++++++++++++++++++++
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/wormdata3.html").read().decode("utf-8")
kdata=html.fromstring(h)
#print(kdata)

tdata=kdata.xpath("/html/body/div/div")[0]
print(tdata.tag)
print(tdata.attrib["id"])

print(tdata.text_content())
#div
dv1
java
+++++++++++++++++++++
tdata=kdata.xpath("/html/body/div/div[2]")[0] #內部從1算起,外部從0算起
print(tdata.tag)
print(tdata.attrib["id"])

print(tdata.text_content())
#div
dv2
c++
=========================
<body>
<a href="http://www.google.com.tw/" id="a">google</a>
</body>
+++++++++++++++++++++++
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata1.html").read().decode("utf-8")
kdata=html.fromstring(h)
#print(kdata)

tdata=kdata.xpath("/html/body/a[1]")[0]#kdata.xpath("/html/body/a")[0]
print(tdata.tag)
print(tdata.attrib["id"])

print(tdata.text_content())
#a
a
google
=====================
from urllib.request import urlopen
from lxml import html

h=urlopen("http://travel.nantou.gov.tw/detail.aspx?type=scenic&id=451").read().decode("utf-8")
kdata=html.fromstring(h)
#print(kdata)

tdata=kdata.xpath("/html/body/div/span/div/div/a")[0]
print(tdata.tag)
print(tdata.attrib["href"].strip())
print(tdata.attrib["id"].strip())

print(tdata.text_content().strip())
#a
#content
A1
跳到主要內容區塊
+++++++++++++++++++++
from urllib.request import urlopen
from lxml import html


h=urlopen("http://travel.nantou.gov.tw/detail.aspx?type=scenic&id=451").read().decode("utf-8")

kdata=html.fromstring(h)
tdata=kdata.xpath("/html/body/div/span/div/nav/div/ul/li")
len1=len(tdata)-1

for i in range(1,len1+1,1):
tdata=kdata.xpath("/html/body/div/span/div/nav/div/ul/li["+str(i)+"]")[0]

print(tdata.text_content().strip())
#網站導覽
常見問題
雙語詞彙
樂旅南投
English
日本語
Thai ver.
相關連結
民意信箱

=======================
<body>
<ul id="ul">
<li>程式設計</li>
    <li>美工設計</li>
    <li>系統設計</li>
    <li>網頁設計</li>
    <li>軟體設計</li>
</ul>
-----------------------
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata3.html").read().decode("utf-8")
kdata=html.fromstring(h)
#print(kdata)

tdata=kdata.xpath("/html/body/ul/li[2]")[0]

print(tdata.text_content())
#美工設計
-------------------------
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata3.html").read().decode("utf-8")
kdata=html.fromstring(h)
#print(kdata)

for i in range(1,5+1,1):
tdata=kdata.xpath("/html/body/ul/li["+str(i)+"]")[0]
print(tdata.text_content())

#程式設計
美工設計
系統設計
網頁設計
軟體設計
================
from urllib.request import urlopen
from lxml import html
from bs4 import BeautifulSoup

h=urlopen("http://192.168.0.53/webproject1/jungdata3.html").read().decode("utf-8")
soup1=BeautifulSoup(h,"html.parser")
list1=soup1.find_all("li")
len1=len(list1)

kdata=html.fromstring(h)
#print(kdata)

for i in range(1,len1+1,1):
tdata=kdata.xpath("/html/body/ul/li["+str(i)+"]")[0]
print(tdata.text_content().strip())

#程式設計
美工設計
系統設計
網頁設計
軟體設計
===============

from urllib.request import urlopen
from lxml import html


h=urlopen("http://192.168.0.53/webproject1/jungdata3.html").read().decode("utf-8")
kdata=html.fromstring(h)
tdata=kdata.xpath("/html/body/ul/li")
len1=len(tdata)

for i in range(1,len1+1,1):
tdata=kdata.xpath("/html/body/ul/li["+str(i)+"]")[0]
print(tdata.text_content().strip())

#程式設計
美工設計
系統設計
網頁設計
軟體設計
==================================
from urllib.request import urlopen
from lxml import html


h=urlopen("http://travel.nantou.gov.tw/detail.aspx?type=scenic&id=451").read().decode("utf-8")

kdata=html.fromstring(h)
cdata=kdata.xpath("/html/body/div/span/div/div/div/ul/span[2]/li")[0]
print(cdata.text_content().strip())


tdata=kdata.xpath("/html/body/div/span/div/div/div/ul/span[2]/li/img")[0]

print(tdata.attrib["src"].strip())
+++++++
from urllib.request import urlopen
from lxml import html


h=urlopen("http://travel.nantou.gov.tw/detail.aspx?type=scenic&id=451").read().decode("utf-8")

kdata=html.fromstring(h)

for i in range(1,4+1,1):
cdata=kdata.xpath("/html/body/div/span/div/div/div/ul/span["+str(i)+"]/li")[0]
print(cdata.text_content().strip())
tdata=kdata.xpath("/html/body/div/span/div/div/div/ul/span["+str(i)+"]/li/img")[0]

print(tdata.attrib["src"].strip())
#

影片下載
1.
2.
3.
4.

-----------------------

from pytube import YouTube

yt=YouTube('https://www.youtube.com/watch?v=uUwWmwEhYoQ&list=PLfr5zCilDSqDrsEiV_BabWUExA6zCvF0H')

video=yt.streams.filter(file_extension='mp4',res='1080p').first()

video.download(r'C:\\tempvideo')

------------------------------
<div id="dv1">
<p>程式設計</p>
    <p>美工設計</p>
    <p>系統設計</p>
    <p>網頁設計</p>
    <p>資料庫設計</p>
</div>
<div id="dv2">
<p>java</p>
    <p>c++</p>
    <p>python</p>
    <p>javascript</p>
    <p>jquery</p>
</div>
---------------------------

from bs4 import BeautifulSoup
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata4.html").read().decode("utf-8")
soup1=BeautifulSoup(h,"html.parser")
list1=soup1.find_all("div")
len1=len(list1)

kdata=html.fromstring(h)
for i in range(1,len1+1,1):
for j in range(1,5+1,1):
tdata=kdata.xpath("/html/body/div["+str(i)+"]/p["+str(j)+"]")[0]
print(tdata.text_content().strip(),end=" ")

print()
===============
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata5.html").read().decode("utf-8")
kdata=html.fromstring(h)
tdata=kdata.xpath("/html/script")[0]
cdata=tdata.text_content().strip()
lenstr=len(cdata)
pdata=cdata.split(";")
len3=len(pdata)
print(len3)
for i in range(0,len3-1,1):
rdata=pdata[i].split("=")
print(rdata[1])



=============
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata4.html").read().decode("utf-8")
kdata=html.fromstring(h)
tdata=kdata.xpath("/html/body/div/p[2]")[0]

print(tdata.getparent().tag)
print(tdata.getnext().tag)

print(tdata.getprevious().tag)
====================
from bs4 import BeautifulSoup
from urllib.request import urlopen
from lxml import html

h=urlopen("http://192.168.0.53/webproject1/jungdata4.html").read().decode("utf-8")
soup1=BeautifulSoup(h,"html.parser")
list1=soup1.find_all("div")
len1=len(list1)

kdata=html.fromstring(h)
for i in range(1,len1+1,1):
for j in range(1,5+1,1):
tdata=kdata.xpath("/html/body/div["+str(i)+"]/p["+str(j)+"]")[0]
print(tdata.text_content().strip(),end=" ")

print()



2019年10月26日 星期六

影像辨識系統般筆記

簡介
環境布置
1.Opencvproject1資料夾於C
2.C:\Python27\Scripts 執行函數庫
 C:\Python27\Lib\site-packages  將cv2.pyd函數庫貼於此
到命令提示字元
C:\Python27\Lib\site-packages  執行
     pip install numpy      矩陣函數庫
     pip install scipy         科學函數庫
     pip install matplotlib  視覺化輸出函數
==========================
import cv2
import numpy as np

print("success")
測試\
Running script: "C:\Opencvproject1\print0.py"
success
==================================
basic1.py
import cv2
import numpy as np
from matplotlib import pyplot as plt

img=cv2.imread("pic1.jpg")

while(1):
cv2.imshow("image",img)

k=cv2.waitKey(1)
if k==ord('q'):
break


cv2.destroyAllWindows()
測視覺化 顯出圖片 按q停止
==============================
python基礎
from __future__ import print_function  #加可用3.0以上版本

a=350

print("a=",a)
================
# -*- coding:UTF-8 -*-   #引入中文化
from __future__ import print_function


print(100,"水果",60,sep="&")
====================
11/02
python-opencv架構

python                   numpy       scipy             matplotlib
基本程式語言      矩陣          科學運算      輸出平台
                opencv
影像識別
讀取影像/圖像/視訊
寫入影像/圖像/視訊
擷取影像/圖像/視訊
影像處理/視訊處理
幾何圖形/視訊處理
模糊 清晰銳利
感興趣區塊
直方圖(曝光分析圖)
機械學習
主焦點框板
多焦點框板
影像焦點追蹤
視訊焦點追蹤
影像/視訊焦點擷取
影像/視訊焦點辨識
文字識別
---------------------------------------

https://docs.opencv.org/3.0-beta/index.html
-------------------
參數化輸出:注意資料型態
print("參數" % 參數名)
print("參數1--參數2" % 參數名)
%d  整數
%s  字串
%f   浮點數

格式化輸出:注意順序
print("字串值:{0}".format("值1"))
print("字串1{0}字串2{1}".format("值1","值 2"))

脫逸字元
\t  --Tab    \n   換行   \b 倒退健    \r 回自首


# -*- coding:UTF-8 -*-
from __future__ import print_function

print(100,"水果",60,sep="&")

print("%s有%d隻小狗" % ("曉明",30))

print("溫度%.2f" % 35.7834)
print("溫度%f" % 35.7834)

print("五的名字是:{0}".format("古力娜砸"))

print("我是:{0},專長是:{1}".format("程式設計師","Java"))

print("{0}\t{1}\t{2}\t{3}\t{4}\n".format("s1001","bill","70/11/04","A","大學"))

-------------------------------------------------------------------
運算子
1.算術運算子  +,-,*,/,%,//,**
2.關係運算子>,<,>=,<=,!=,==
3.邏輯運算子and,or,not
4.指定運算子+=,-=,*=,/=

b=True
print(int(b))
-----------------------------------
from __future__ import print_function

name=raw_input("請輸入姓名:")

print("姓名:{0}".format(name))
----------------------------------------
x=int(raw_input("數值一:"))
y=int(raw_input("數值二:"))
total=x+y

print("%d+%d=%d" % (x,y,total))
--------------

a=10;b=50
x=(a>=20) and (b<=100)

print(x)
-------
a=30;b=50

if (a>=20) and (b<=100):
print("條件成立")
else:

print(x)
-----------------------------
a=30;b=50

if (a>=20) or (b<=100):
print("條件成立")
else:

print("條件不成立")
-------------------------
a=30;b=50

if not((a>=20) or (b<=100)):
print("條件成立")
else:

print("條件不成立")
----------------------------------
位元運算子&
1.數值轉2進制
2.參考真值表
3.再轉為數值
ex  x=5
y=3
sum=5|3
print(sum) #7
----------------------
from __future__ import print_function

sum=8>>2
print(sum,"\n")

total=8<<2

print(total)
--------------------------
from __future__ import print_function
x=int(raw_input("國文:"))
y=int(raw_input("英文:"))
z=int(raw_input("數學:"))

sum=x+y+z
avg=sum/3
print("國文\t英文\t數學\t總分\t平均\n")

print("%d\t%d\t%d\t%d%.2f" % (x,y,z,sum,avg))
--------------------------------------------------------
num=int(raw_input("請輸入0-100數值:"))
if (num>=0) and (num<=100):
print("正常範圍值")
else:

print("超出")
===========
score=int(raw_input("請輸入分數:"))

if score>=90:
print("A")
elif score>=80:
print("B")
elif score>=70:
print("c")
elif score>=60:
print("D")
else:

print("不及格")
-------------------------
id=raw_input("帳號:")
pas=raw_input("密碼:")

if id=="p1003" and pas=="chin":
print("登入系統")
else:

print("登入失敗")
---------------------------------
range
n1=range(5)
n2=range(1,5+1)
n3=range(1,10,2)
n4=range(2,10+1,2)
n5=range(5,1-1,-1)
print(list(n1))
print(list(n2))
print(list(n3))
print(list(n4))

print(list(n5))
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]

[5, 4, 3, 2, 1]
---------------------
ASCII
97-122 小寫英文字母
65-90  大寫
chr()ASCII轉字母
ord()字母轉ASCII
int()
float()
str()
---------------------------
from __future__ import print_function
for i in range(1,10+1,1):

print(i,end="\t")
______________________________
from __future__ import print_function

for i in range(65,90+1,1):

print(chr(i),end="")
____________________________________
11/9  exercise
from __future__ import print_function
t100=0
t100o=0
t100e=0
t10037=0
for i in range(1,100+1)://ex1
t100=t100+i
print(t100)
for i in range(1,100+1)://ex2
if (i%2)!= 0:
t100o=t100o+i
print(t100o)

for i in range(1,100+1,2)://ex3
t100e=t100e+i
print(t100e)

for i in range(1,100+1,1)://ex4
if ((i%3)==0):
t10037=t10037+i
if ((i%7)==0):
t10037=t10037+i
if (((i%3)==0)and((i%7)==0)):
t10037=t10037-i

print(t10037)

for i in range(1,9+1,1)://ex5
for j in range(1,9+1,1):
print("%d*%d=" % (i,j),i*j,end=("\t"))
print()

for i in range(1,6)://break
if i==4:
break
print(i)
for i in range(1,11)://continue
if i==6:
continue
print(i)

n=0//ex6
str1=""
m=0
str2=""
for i in range(97,106,1):
if i%2==0:
n=n+1
str1+=chr(i)
if i%2!=0:
m=m+1
str2+=chr(i)

print("偶數字元:%s....%d個" % (str1,n))

print("偶數字元:%s....%d個" % (str2,m))
***********
5050//ex1
2500//ex2
2500//ex3
2208//ex4
//ex5
1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9
2*1= 2 2*2= 4 2*3= 6 2*4= 8 2*5= 10 2*6= 12 2*7= 14 2*8= 16 2*9= 18
3*1= 3 3*2= 6 3*3= 9 3*4= 12 3*5= 15 3*6= 18 3*7= 21 3*8= 24 3*9= 27
4*1= 4 4*2= 8 4*3= 12 4*4= 16 4*5= 20 4*6= 24 4*7= 28 4*8= 32 4*9= 36
5*1= 5 5*2= 10 5*3= 15 5*4= 20 5*5= 25 5*6= 30 5*7= 35 5*8= 40 5*9= 45
6*1= 6 6*2= 12 6*3= 18 6*4= 24 6*5= 30 6*6= 36 6*7= 42 6*8= 48 6*9= 54
7*1= 7 7*2= 14 7*3= 21 7*4= 28 7*5= 35 7*6= 42 7*7= 49 7*8= 56 7*9= 63
8*1= 8 8*2= 16 8*3= 24 8*4= 32 8*5= 40 8*6= 48 8*7= 56 8*8= 64 8*9= 72
9*1= 9 9*2= 18 9*3= 27 9*4= 36 9*5= 45 9*6= 54 9*7= 63 9*8= 72 9*9= 81
//break
1
2
3
//continue
1
2
3
4
5
7
8
9
10
//ex6
偶數字元:bdfh....4個
偶數字元:acegi....5個

_____________________________
字串
str1="Hello Python!"
len1=len(str1)

print("字串長度;%d" % len1)
-----------------------
str1=" Hello Python! "

print(str1.strip())
print(str1.lstrip())

print(str1.rstrip())
//HELLO PYTHON!
hello python!
-1
6
---------------------------------
str1="Hello Python!"
print(str1.upper())
print(str1.lower())
s=str1.find('p')
print(s)
s=str1.find('P')

print(s)
----------
str1="Hello python"
s=str1.replace("python","Java")

print(s)
------------
str1="Hello Python"
len1=len(str1)

for i in range(0,len1,1):
if str1[i].isupper():
print(str1[i])
for i in str1:
print(i,type(i))


t=str1.startswith("He")
t1=str1.endswith("on")
print(t)

print(t1)
================
str1="Oracle Java Develement Studio"

n=0
for i in str1:
if i in 'a':
n+=1

print(n)
---------------------
Slice    ====
str1="AI Python Program"

s=str1[3:]
print(s)

s1=str1[:10]
print(s1)

s2=str1[3:10]
print(s2)

s3=str1[-1]

print(s3)
==
Python Program
AI Python
Python

m
-----------------------------------
import random as r

for i in range(1,5+1):
print("%.1f" % r.random())

for i in range(1,5+1):
v=r.randint(1,100)
print(v)
for i in range(1,5+1):
v1=r.randrange(1,100,3)

print(v1)
----------------------
串列
1.直接表示法
2.不定長度表示法
3.
a=[10,20,30,40,50]

print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[4])

len1=len(a)
for i in range(0,len1,1):
print(a[i])

a1=[12,56,99,21,52]
len1=len(a1)
for i in range(len1-1,0-1,-1):
print(a[i])

print(max(a1))
print()
print(min(a1))
print()

c=sorted(a1)
c1=sorted(a1,reverse=True)
total=sum(a)
for i in range(0,len1):
print(c[i])
for i in range(0,len1):
print(c1[i])

print(total)
---------------------
list ex1
list1=[10,20,30,40,50]

num=int(raw_input("請輸入0-100數值:"))

if num in list1:
print("%d在串列中" % num)
else:

print("%d不在串列中" % num)
-------------------------------

mylist1=[]
qp="delphi"
mylist1.append("java")
mylist1.append("javascript")
mylist1.append("delphi")
mylist1.append(30)
mylist1.append("c++")
mylist1.append("A")
mylist1.append("jQuery")
mylist1.append(True)
mylist1.insert(2,"php")
mylist1.remove(qp)

for i in mylist1:

print(i)
======================
dict字典{}
dict1={"java":350,"c++":250,"html":150,"css":100,"lua":450}

len1=len(dict1)
print(len1)

print(dict1["java"])
print(dict1["c++"])
print(dict1["html"])
print(dict1["css"])
print(dict1["lua"])

k=list(dict1.keys())
print(k)
for i in range(0,len1):

print(k[i])

v=list(dict1.values())
len2=len(v)
for i in range(0,len2):

print(v[i])
_____________________
5
350
250
150
100
450
['lua', 'html', 'java', 'css', 'c++']
lua
html
java
css

c++
450
150
350
100

250
------
data={"java":350,"c++":250,"html":150,"css":100,"lua":450}

it=list(data.items())
len1=len(it)

for i in range(0,len1):

print(list(it[i]))
===============
['lua', 450]
['html', 150]
['java', 350]
['css', 100]
['c++', 250]
--------------------------
11/17
影像結構

二位陣列
import numpy as np

a=np.array([12,13,14])

len1=len(a)
print(len1)
print(a)

for i in range(0,len1):

print(a[i])
______________________
import numpy as np

b=np.array([[12,56],[34,78]])
len1=len(b)
len2=len(b[0])

for i in range (0,len1):
    for j in range(0,len2):

         print(b[i][j])  #12 56 34 78
_________________________

import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a)
print()
b=a.reshape(3,2)
print(b)
len1=len(b)
len2=len(b[0])
for i in range(0,len1):
     for j in range(0,len2):
         print(b[i][j])
______________________
[[1 2 3]
[4 5 6]]

[[1 2]
[3 4]
[5 6]]
1
2
3
4
5
6

---------
import numpy as np

a=np.arange(9).reshape(3,3)
print(a)
b=np.arange(24)
print(b)
x=np.array([1,2,3,4,5],dtype=np.int64)

print(x)
#[[0 1 2]
[3 4 5]
[6 7 8]]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[1 2 3 4 5]
--------------

import numpy as np

x=np.zeros((5),dtype=np.int)#一維
print(x)
y=np.zeros((5,5),dtype=np.uint8)#二維

print(y)
#[0 0 0 0 0]
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
-------------------------------

import numpy as np
import cv2


img=cv2.imread("pic1.jpg")
total=img.shape
print(total)

sum=img.size
print(sum)


print(img[100,100,1])
#(170, 255, 3)
130050
92
_____________________
_import numpy as np
import cv2


img=cv2.imread("x3.jpg")
total=img.shape
print(total)
rtotal=0
for i in range(0,170):
    for j in range(0,250):
          rtotal=rtotal+img[i,j,2]
print(rtotal)

gtotal=0
for i in range(0,170):
     for j in range(0,250):
          gtotal=gtotal+img[i,j,1]
print(gtotal)

btotal=0
for i in range(0,170):
     for j in range(0,250):
         btotal=btotal+img[i,j,0]
print(btotal)
#__(201, 251, 3)
1838463
4174231
7823176
__________________
import numpy as np

x=np.ones((2,3),dtype=np.uint8)
print(x)
print("")
x[0][0]=215
x[0][1]=115
x[0][2]=45
x[1][0]=32
x[1][1]=125
x[1][2]=200


print(x)
#[[1 1 1]
[1 1 1]]

[[215 115 45]
[ 32 125 200]]
_______________
np.asarray
import numpy as np

x=[1,2,3,4,5,6]
y=np.asarray(x)

print(y)
--------------------
import numpy as np
import cv2


img=cv2.imread("pic1.jpg")
total=img.shape
print(total)

sum=img.size
print(sum)


print(img[100,100,1])
#(170, 255, 3)
130050
92
===================
import numpy as np
import cv2


img=cv2.imread("x3.jpg")
total=img.shape
print(total)
rtotal=0
for i in range(0,170):
   for j in range(0,250):
       rtotal=rtotal+img[i,j,2]
print(rtotal)

gtotal=0
for i in range(0,170):
    for j in range(0,250):
           gtotal=gtotal+img[i,j,1]
print(gtotal)

btotal=0
for i in range(0,170):
            for j in range(0,250):
                   btotal=btotal+img[i,j,0]

print(btotal)
#(201, 251, 3)
1838463
4174231
7823176偏藍
=========================
11/23
import numpy as np

x=[1,2,3,4,5]
#y=np.asarray(x,dtype=np.float)     #1.0 2.0 3.0 4.0 5.0
y=np.asarray(x,dtype=np.uint8)  #1 2 3 4 5
len1=len(y)
for i in range(0,len1):
    print(y[i])
--------------------------------------
from __future__ import print_function
import numpy as np

s="Hello Opencv"
#y=np.asarray(x,dtype=np.float)
x=np.frombuffer(s,dtype="S1")
len1=len(x)
for i in range(0,len1):

print(x[i],end='')
#['H' 'e' 'l' 'l' 'o' ' ' 'O' 'p' 'e' 'n' 'c' 'v']
Hello Opencv
--------------------------
import numpy as np

n1=np.array([1,3,5,6,2,3])
n2=np.array([3,7,1,7,8,2])
n3=n1+n2

print(n3.reshape(3,2))
#[[ 4 10]
[ 6 13]
[10 5]]

import numpy as np

mydata=[]
n1=np.array([1,3,5,6,2,3])
n2=np.array([3,7,1,7,8,2])
len1=len(n1)
for i in range(0,len1):
       mydata.append(n1[i]+n2[i])
n3=np.array(mydata).reshape(3,2)

print(n3)
#[[ 4 10]
[ 6 13]
[10 5]]
=====================
https://www.geeksforgeeks.org/python-detect-polygons-in-an-image-using-opencv/
Open CV: Java/c/c++/python/android跨平台
1.cv2.__VERSION版本編號
2.cv2.imread(圖片路徑,1)
   cv2.imread(圖片路徑,0)
3.cv2.imshow("抬頭名稱",圖片元件)
4.cv2.waitKey(0)等候鍵盤按鍵
5.cv2.destropAllWindows()釋放記憶體空間

import cv2

print cv2.__version__
#image=cv2.imread("x1.jpg",1)
image=cv2.imread("x1.jpg",0)
cv2.imshow("demo",image)
k=cv2.waitKey(0)
if cv2.waitKey(0) & 0xFF == ord('q'):

cv2.destroyAllWindows()
====================
按q鍵結束
k=cv2.waitKey(0)
if  k==ord('q'):
      break
1.矩陣像素元件
image[i,j]
2.圖像大小解析度
shape==>[高,寬,通道數]
#imgread1.py
import cv2
import numpy as np

img=cv2.imread("pic1.jpg")
len1=img.shape
print(len1)

print("height:",len1[0])
print("width:",len1[1])

print("turnel:",len1[2])
#(170, 255, 3)
('height:', 170)
('width:', 255)
('turnel:', 3)
=========================
from __future__ import print_function
import numpy as np
import cv2


img=cv2.imread("x3.jpg")
for i in range(10,20+1):
for j in range(10,20+1):
img[i,j]=[255,255,255]
while (1):
cv2.imshow("image",img)
k=cv2.waitKey(0)
if k==ord('q'):
break

cv2.destroyAllWindows()
====================
from __future__ import print_function
import numpy as np
import cv2


img=cv2.imread("x3.jpg")
cv2.namedWindow("image",cv2.WINDOW_NORMAL)#openvc自訂視窗
cv2.resizeWindow("image",800,500)

len=img.shape #值不變
print(len)

len1=img.size #不變
print(len1)

while (1):
cv2.imshow("image",img)
k=cv2.waitKey(0)
if k==ord('q'):
break

cv2.destroyAllWindows()
#(201, 251, 3)
151353
----------------------------------------------
ex1
from __future__ import print_function
import numpy as np
import cv2

k=int(raw_input("選單(1)200*100(2)500*300(3)800*500,請選擇:"))

img=cv2.imread("x1.jpg")
cv2.namedWindow("image",cv2.WINDOW_NORMAL)

if k==1:
cv2.resizeWindow("image",200,100)
elif k==2:
cv2.resizeWindow("image",500,300)
elif k==3:
cv2.resizeWindow("image",800,500)

while (1):
cv2.imshow("image",img)
k1=cv2.waitKey(0)
if k1==ord('q'):
break

cv2.destroyAllWindows()
========================
ex2
from __future__ import print_function
import numpy as np
import cv2

k=int(raw_input("選單(1)圖一(2)圖二(3)圖三,請選擇:"))
if k==1:
img=cv2.imread("x1.jpg")
elif k==2:
img=cv2.imread("x2.jpg")
elif k==3:
img=cv2.imread("x3.jpg")

cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",800,500)

while (1):
cv2.imshow("image",img)
k1=cv2.waitKey(0)
if k1==ord('q'):
break

cv2.destroyAllWindows()
==============================
ex3
from __future__ import print_function
import numpy as np
import cv2

while (1):
k=int(raw_input("選單(1)圖片一(2)圖片二(3)圖片三(4)結束 請選擇:"))
if k==1:
img=cv2.imread("x1.jpg")
elif k==2:
img=cv2.imread("x2.jpg")
elif k==3:
img=cv2.imread("x3.jpg")
elif k==4:
break

cv2.imshow("image",img)
k1=cv2.waitKey(0)
if k1==ord('q'):
break

cv2.destroyAllWindows()
=================
正常程序
from __future__ import print_function
import numpy as np
import cv2

def menuitem():
try:
k=int(raw_input("選單(1)圖片一(2)圖片二(3)圖片三(4)結束 請選擇:"))
if k==1:
img=cv2.imread("x1.jpg")
elif k==2:
img=cv2.imread("x2.jpg")
elif k==3:
img=cv2.imread("x3.jpg")
elif k==4:
quit

showvalue(img)
except:
print("")

def showvalue(im):
try:
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",800,500)

while (1):
cv2.imshow("image",im)
k1=cv2.waitKey(0)
if k1==ord('q'):
break
cv2.destroyAllWindows()
menuitem()
except:
print("")

if __name__=="__main__":

menuitem()
==================
https://www.geeksforgeeks.org/python-detect-corner-of-an-image-using-opencv/
=====================
同時秀兩張
from __future__ import print_function
import numpy as np
import cv2

img=cv2.imread("x3.jpg")
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",800,500)
img2=cv2.imread("x2.jpg")
cv2.namedWindow("image1",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image1",800,500)



while (1):
cv2.imshow("image",img)
cv2.imshow("image1",img2)
k=cv2.waitKey(0)
if k==ord('q'):
break
cv2.destroyAllWindows()

====================
模糊一
from __future__ import print_function
import numpy as np
import cv2

img=cv2.imread("x3.jpg")
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",800,500)
blur=cv2.blur(img,(5,5))
cv2.namedWindow("blur",cv2.WINDOW_NORMAL)
cv2.resizeWindow("blur",800,500)

while (1):
cv2.imshow("image",img)
cv2.imshow("blur",blur)
k=cv2.waitKey(0)
if k==ord('q'):
break
cv2.destroyAllWindows()
============================


from __future__ import print_function
import numpy as np
import cv2


img=cv2.imread("x3.jpg",cv2.IMREAD_COLOR)
#img=cv2.imread("x3.jpg",1)
cv2.imwrite("hope1.jpg",img)
print("success")
while (1):
cv2.imshow("image",img)
k=cv2.waitKey(0)
if k==ord('q'):
break

cv2.destroyAllWindows()
==
matplotlib

import numpy as np
import cv2
from matplotlib import pyplot as plt

img=cv2.imread("pic3.jpg")
img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

plt.imshow(img_rgb)

plt.show()
+++++++++++++++++++
灰白\
img=cv2.imread("pic3.jpg",cv2.IMREAD_GRAYSCALE)


plt.imshow(img,cmap="gray")

plt.show()
====================
import numpy as np
import cv2
from matplotlib import pyplot as plt

img=cv2.imread("pic3.jpg")
img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)



plt.imshow(img,cmap="gray")

plt.show()
+++++++++++++++++++++
import cv2
import numpy as np
from matplotlib import pyplot as plt

img=cv2.imread("pic1.jpg")
img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
img2=cv2.imread("pic2.jpg")
img2_rgb=cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)

plt.subplot(121)
plt.imshow(img_rgb)
plt.subplot(122)
plt.imshow(img2_rgb)


plt.show()
+++++++++++++++++++++++++
import cv2
import numpy as np
from matplotlib import pyplot as plt

img=cv2.imread("pic1.jpg")
img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
img2=cv2.imread("pic2.jpg")
img2_rgb=cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
img3=cv2.imread("pic3.jpg")
img3_rgb=cv2.cvtColor(img3,cv2.COLOR_BGR2RGB)
img3_gray=cv2.cvtColor(img3,cv2.IMREAD_GRAYSCALE)

plt.subplot(221)#安排兩列兩行的排版
plt.imshow(img_rgb)
plt.subplot(222)
plt.imshow(img2_rgb)
plt.subplot(223)
plt.imshow(img3_rgb)
plt.subplot(224)
plt.imshow(img3_gray,cmap='gray')


plt.show()
-------------------------
https://kknews.cc/zh-tw/code/gg2bej8.html
11/30
import numpy as np
import cv2
from matplotlib import pyplot as plt

#讀取圖檔
img=cv2.imread("C:\\openCVproject1\\fish1.jpg")
#轉為灰階
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#計算質方圖每個bin數值[影像,通道,遮罩,區間數量質方圖,像素質範圍]
hist1=cv2.calcHist([img],[0],None,[256],[0,256])
hist2=cv2.calcHist([img],[1],None,[256],[0,256])
hist3=cv2.calcHist([img],[2],None,[256],[0,256])


#劃出分布圖
plt.plot(hist1)
plt.plot(hist2)
plt.plot(hist3)
plt.show()

https://blog.gtwang.org/programming/python-opencv-matplotlib-plot-histogram-tutorial/
https://morvanzhou.github.io/tutorials/data-manipulation/plt/2-3-axis1/
https://www.kancloud.cn/aollo/aolloopencv/263215
http://www2.nkfust.edu.tw/~shanhuen/PythonTutorialHtml/Matplotlib/Matplotlib1.html
---------------------------
12/07
import cv2

cv2.namedWindow("frame")
cap=cv2.VideoCapture(0)


while(True):
ret,img=cap.read()

if ret==True:
cv2.imshow("frame",img)
k=cv2.waitKey(1)

if k==ord("z") or k==ord("Z"):
cv2.imwrite("C:\\openCVproject1\\media\\ft.jpg",img)
break

cap.release()
cv2.waitKey(0)

cv2.destroyWindow("frame")
------------------------------------------------
opencv畫布
np.zeros((512,512,3.),np.uint8) 黑色畫布
線條
----------------------
import numpy as np
import cv2

img=np.zeros((512,512,3),np.uint8)
cv2.line(img,(10,30),(200,30),(0,0,255),5)
cv2.imshow("drawline",img)
cv2.waitKey(0)

cv2.destroyAllwindows()
---------------------------
import numpy as np
import cv2

img=np.zeros((512,512,3),np.uint8)+255
cv2.line(img,(10,30),(200,30),(0,0,255),5)
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",500,250)
cv2.imshow("image",img)
cv2.waitKey(0)

cv2.destroyAllWindows()
-----------------------------
import numpy as np
import cv2
import time

k=1
img=cv2.imread("../x1.jpg")
total=img.shape

#img=np.zeros((512,512,3),np.uint8)+255
for i in range(0,total[0],20):
if ((k%2)==0):
cv2.line(img,(0,i),(total[1],i),(255,0,0),5)
else:
cv2.line(img,(0,i),(total[1],i),(0,255,0),5)
k=k+1

#cv2.line(img,(0,500),(500,0),(0,0,255),5)
#cv2.namedWindow("image",cv2.WINDOW_NORMAL)
#cv2.resizeWindow("image",500,250)
cv2.imshow("image",img)
cv2.waitKey(0)

cv2.destroyAllWindows()
-----------------------------------------------
cv2.rectangle(img,(100,100),(200,200),(0,0,255),5) #畫矩形

cv2.ellipse(img,(250,250),(100,100),0,0,360,(0,0,255),-1)
----------------------------------
import numpy as np
import cv2
import random as ra

src=cv2.imread("../x1.jpg")
res=cv2.resize(src,(512,512),interpolation=cv2.INTER_CUBIC)
img=np.zeros((512,512,3),np.uint8)+255

total=img.shape
for i in range(100+1):
x=ra.randint(0,512)
y=ra.randint(0,512)
b=ra.randint(0,255)
g=ra.randint(0,255)
r=ra.randint(0,255)
cv2.circle(img,(x,y),10,(b,g,r),1)

wimg=cv2.addWeighted(res,0.2,img,0.4,0)

cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",512,512)
cv2.imshow("image",img)
cv2.waitKey(0)

cv2.destroyAllWindows()
--------------------------
import numpy as np
import cv2

img=np.zeros((512,512,3),np.uint8)+255

cv2.putText(img,'Hello OPENCV',(50,150),cv2.FONT_HERSHEY_SCRIPT_COMPLEX,1,(0,0,255),2)
cv2.putText(img,'Hello OPENCV',(50,180),cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,1,(0,0,255),2)
cv2.putText(img,'Hello OPENCV',(50,210),cv2.FONT_HERSHEY_DUPLEX,1,(0,0,255),2)
cv2.putText(img,'Hello OPENCV',(50,240),cv2.FONT_HERSHEY_TRIPLEX,1,(0,0,255),2)
cv2.putText(img,'Hello OPENCV',(50,270),cv2.FONT_ITALIC,1,(0,0,255),2)

#cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",1000,500)
while True:
cv2.imshow("draweclips",img)
k=cv2.waitKey(0)
if k==ord('q'):
break


cv2.destroyAllWindows()
--------------------------------------------
import numpy as np
import cv2

str1="java,c++,delphi,javascript,pascal"
data=str1.split(',')
len1=len(data)
print(len1)
k=150
img=np.zeros((512,512,3),np.uint8)+255
for i in range(0,len1,1):
cv2.putText(img,str(i+1)+':'+data[i],(50,k),cv2.FONT_HERSHEY_SCRIPT_COMPLEX,1,(0,0,255),2)
k=k+30




#cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",1000,500)
while True:
cv2.imshow("putText",img)
k=cv2.waitKey(0)
if k==ord('q'):
break


cv2.destroyAllWindows()
------------------------
import numpy as np
import cv2

def nothing(x):
pass

img=np.zeros((512,512,3),np.uint8)+255
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",600,500)
cv2.createTrackbar("R","image",0,255,nothing)
cv2.createTrackbar("G","image",0,255,nothing)
cv2.createTrackbar("B","image",0,255,nothing)



while True:
cv2.imshow("image",img)
r=cv2.getTrackbarPos("R","image")
g=cv2.getTrackbarPos("G","image")
b=cv2.getTrackbarPos("B","image")
img[:]=[b,g,r]
k=cv2.waitKey(1)
if k==ord('q'):
break


cv2.destroyAllWindows()
-------------------------------------------
import numpy as np
import cv2

def nothing(x):
r=cv2.getTrackbarPos("R","image")
g=cv2.getTrackbarPos("G","image")
b=cv2.getTrackbarPos("B","image")
img[:]=[b,g,r]
cv2.imshow("image",img)

img=np.zeros((512,512,3),np.uint8)
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.resizeWindow("image",600,500)
cv2.createTrackbar("R","image",0,255,nothing)
cv2.createTrackbar("G","image",0,255,nothing)
cv2.createTrackbar("B","image",0,255,nothing)
cv2.imshow("image",img)



while True:
k=cv2.waitKey(0)
if k==ord('q'):
break


cv2.destroyAllWindows()
----------------------------------------
import numpy as np
import cv2

d=False
point1=()
point2=()

def draw_rect(event,x,y,flags,param):
global point1,point2,d
if event==cv2.EVENT_LBUTTONDOWN:
if d==False:
d=True
point1=(x,y)
else:
d=False

elif event==cv2.EVENT_RBUTTONDOWN:
if d==True:
point2=(x,y)



img=np.zeros((512,512,3),np.uint8)+255
cv2.namedWindow('image')
cv2.setMouseCallback("image",draw_rect)

while True:

if point1 and point2:
cv2.rectangle(img,point1,point2,(0,255,0),3)
point1=()
point2=()

cv2.imshow("image",img)
if cv2.waitKey(1)==ord('q'):
break


cv2.destroyAllWindows()
-----------------------
import dlib
import imutils
import cv2

img=cv2.imread("human01.jpg")
img=imutils.resize(img,width=1200)
detector=dlib.get_frontal_face_detector()
face_rects=detector(img,0)
for i ,d in enumerate(face_rects):
x1=d.left()
y1=d.top()
x2=d.right()
y2=d.bottom()
cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),4)
cv2.imshow("Face-detection",img)
cv2.waitKey(0)

cv2.destroyAllWindows()
----------------------------------
12/14
http://www.kancloud.cn:8080/aollo/aolloopencv/261446
-------------
import cv2

cv2.namedWindow("frame")
cap=cv2.VideoCapture(0)


while(True):
ret,img=cap.read()

if ret==True:
cv2.imshow("frame",img)
k=cv2.waitKey(1)

if k==ord("z") or k==ord("Z"):
cv2.imwrite("C:\\openCVproject1\\1214\\media\\ft.jpg",img)
break

cap.release()
cv2.waitKey(0)

cv2.destroyWindow("frame")
-----------------------------
waitKey(1) 中的数字代表等待按键输入之前的无效时间,单位为毫秒,在这个时间段内按键 ‘q’ 不会被记录,在这之后按键才会被记录,并在下一次进入if语段时起作用。也即经过无效时间以后,检测在上一次显示图像的时间段内按键 ‘q’ 有没有被按下,若无则跳出if语句段,捕获并显示下一帧图像。

若此参数置零,则代表在捕获并显示了一帧图像之后,程序将停留在if语句段中一直等待 ‘q’ 被键入。

cv2.waitKey(1) 与 0xFF(1111 1111)相与是因为cv2.waitKey(1) 的返回值不止8位,但是只有后8位实际有效,为避免产干扰,通过 ‘与’ 操作将其余位置0。
__________________________
import cv2

cv2.namedWindow("frame")
cap=cv2.VideoCapture(0)
n=0

while(True):
ret,img=cap.read()

if ret==True:
cv2.imshow("frame",img)
k=cv2.waitKey(1)

if k==ord("w") or k==ord("W"):
n=n+1
d="C:\\Opencvproject1\\1214\\media\\ft"+str(n)+".jpg"
cv2.imwrite(d,img)

if k==ord("z") or k==ord("Z"):
break

cap.release()
cv2.waitKey(0)

cv2.destroyWindow("frame")
____________________________
import numpy as np
import cv2

cap=cv2.VideoCapture("vi.avi")
n=0

while(True):
try:
ret,img=cap.read()
cv2.imshow("frame",img)
if cv2.waitKey(0)==ord('q'):
break
except:
print("end.....")
cap.release()
cv2.destoryAllwindows()
break


cap.release()


cv2.destroyAllWindowsWindow()
---------------------
讀取喜歡的影格,並存下
import numpy as np
import cv2

cap=cv2.VideoCapture("vi.avi")
n=0

while(True):
try:
ret,img=cap.read()
if ret==True:
cv2.imshow("frame",img)
k=cv2.waitKey(50)
if k==ord('q'):
cap.release()
cv2.destoryAllwindows()
break

if k==ord('z') or k==ord("Z"):
cv2.imwrite("C:\\Opencvproject1\\1214\\media\\ft"+str(n)+".jpg",img)
n=n+1
else:
cap.release()
cv2.destoryAllwindows()
break


except:
print("end.....")
cap.release()
cv2.destoryAllwindows()
break


cap.release()

cv2.destroyAllWindowsWindow()
--------------------------
import cv2

cv2.namedWindow("frame")
cap=cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(*'DIB ')
out=cv2.VideoWriter("C:\\Opencvproject1\\1214\\media\\output7.avi",fourcc,3.0,(640,480))

while(True):
ret,img=cap.read()
if ret==True:
frame=cv2.flip(img,1)
out.write(frame)
cv2.imshow("frame",img)
k=cv2.waitKey(1)
if k==ord('q'):
break


cap.release()
out.release()

cv2.destroyWindow("frame")
-------------------------------
擷取送至網頁輸出
import numpy as np
import cv2
import os

cap=cv2.VideoCapture(0)
n=1

while(True):
try:
ret,img=cap.read()
if ret==True:
cv2.imshow("frame",img)
k=cv2.waitKey(1)
if k==ord('q'):
cap.release()
cv2.destroyAllWindows()
os.system('"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" C:\\Opencvproject1\\1214\\media\\chindata3.html')
break

if k==ord('z') or k==ord("Z"):
cv2.imwrite("C:\\Opencvproject1\\1214\\media\\chin"+str(n)+".jpg",img)
n=n+1
if n==6:
n=1
else:
cap.release()
cv2.destoryAllwindows()
break


except:
print("end.....")
cap.release()
cv2.destroyAllWindows()
break


cap.release()
cv2.destroyAllWindows()

------------------------------------
<script language="javascript" src="jquery-3.4.1.min.js"></script>
<script language="javascript">
  $(document).ready(function()
  {
  $("a img").click(function()
  {
  var k=$(this).attr("src");
  $("#total").attr("src",k);
  });

  $("#tab1 tr td").mouseover(function()
  {
  $(this).css("background-color","pink");
  });

  $("#tab1 tr td").mouseleave(function()
  {
  $(this).css("background-color","transparent");
  });
  });
</script>
<body>
<div id="dv1" style="width:1050px;height:180px; background-color:#9CF;">
<table border="0" width="1050" id="tab1" height="180" >
  <tr>
    <td align="center">
      <a href="javascript:void;" id="a1" >
       <img id="img1" src="chin1.jpg" width="200" height="150" />
      </a>
    </td>
    <td align="center">
      <a href="javascript:void;" id="a2" >
       <img id="img2" src="chin2.jpg" width="200" height="150" />
      </a>
    </td>
    <td align="center">
      <a href="javascript:void;" id="a3">
       <img id="img3" src="chin3.jpg" width="200" height="150" />
      </a>
    </td>
    <td align="center">
      <a href="javascript:void;" id="a4">
       <img id="img4" src="chin4.jpg" width="200" height="150" />
      </a>
    </td>
    <td align="center">
      <a href="javascript:void;" id="a5">
       <img id="img5" src="chin5.jpg" width="200" height="150" />
      </a>
    </td>
  </tr>
</table>
</div>
<p>
<div id="dv1" style="width:1010px;height:570px; background-color:#000; padding:20px">
  <img id="total" src="chin1.jpg" width=1000 height=550 />
</div>
</body>
</html>
---------------------
import numpy as np
import cv2
import dlib
import imutils

cap=cv2.VideoCapture(0)
detector=dlib.get_frontal_face_detector()

while(cap.isOpened()):
ret,frame=cap.read()
face_rects=detector(frame,0)
for i,d in enumerate(face_rects):
x1=d.left()
y1=d.top()
x2=d.right()
y2=d.bottom()

cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),4)
        #text="Hello"
#cv2.putText(frame,text,(x1,y1),cv2.FONT_HERSHEY_PLAIN,0.7,(255,255,255),1)
cv2.imshow('frame',frame)
if cv2.waitKey(1)==ord('q'):
break

cap.release()


cv2.destroyAllWindows()

dlib.get_frontal_face_detector()
----------------------------
import numpy as np
import cv2
import dlib
import imutils

cap=cv2.VideoCapture(0)
detector=dlib.get_frontal_face_detector()

while(cap.isOpened()):
ret,frame=cap.read()
face_rects=detector(frame,0)
for i,d in enumerate(face_rects):
x1=d.left()
y1=d.top()
x2=d.right()
y2=d.bottom()

img=cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),4)
faceimg=frame[y1:y2,x1:x2]
k=cv2.waitKey(1)
if k==ord("z") or k==ord("Z"):
cv2.imwrite("C:\\Opencvproject1\\1214\\media\\face1.jpg",faceimg)

cv2.imshow('frame',frame)
#cv2.imread("C:\\Opencvproject1\\1214\\media\\face1.jpg",img)
if cv2.waitKey(1)==ord('q'):
break

cap.release()


cv2.destroyAllWindows()
-------------------------------------------